javascript - how add element to scrollmenu html with js function
问题描述
i have a scroll menu , and in my java script file i read some data from database and i want to add this data to the scrollmenu. im very new to web development and i donnt have any notion anout what i have to do. i need for example a funtion that add a new item to the scrollmenu, and it shold be clickable.
this is the html code.
<html>
<div class="scrollmenu" id = "scroll">
<a href="#col1">Home</a>`
<a href="#col2">News</a>
<!-- i want to add at the javascript col3 -->
</div>
</html>
解决方案
这是一个带有添加项按钮的示例,基本上您会听到单击Add a new item
按钮,然后执行在菜单中添加新链接项的操作:
var el = document.getElementById('addItem');
el.addEventListener('click', function(e) {
var menu = document.getElementById('scroll');
var a = document.createElement('a');
a.setAttribute('href', '#col3');
a.innerHTML = 'New Item';
menu.appendChild(a);
});
<button id="addItem">
Add a new item
</button>
<br><br>
<div class="scrollmenu" id = "scroll">
<a href="#col1">Home</a>
<a href="#col2">News</a>
</div>
如果您希望它更加动态,您可以创建一个函数并将链接的文本和 href 作为参数传递,如下所示:
var el = document.getElementById('addItem');
el.addEventListener('click', function(e) {
addNewItem('New Link', '#col3');
});
function addNewItem(itemText, itemLink) {
var menu = document.getElementById('scroll');
var a = document.createElement('a');
a.setAttribute('href', itemLink);
a.innerHTML = itemText;
menu.appendChild(a);
}
<button id="addItem">
Add a new item
</button>
<br><br>
<div class="scrollmenu" id = "scroll">
<a href="#col1">Home</a>
<a href="#col2">News</a>
</div>
推荐阅读
- python - 'int' 对象没有属性 'append' 没有真正的原因
- javascript - ASP.net 找不到 javascript 函数
- azure - 使用带有 Flask 的 Azure Functions,我如何实现 2 个 Azure 函数 webhook 以同时从控制台运行
- node.js - 无法 Docker 将基于 nuxt 的快速服务器端口转发到主机
- java - 为什么我的计时器没有每秒打印一次?
- spring-boot - 使用 Sprint Boot 和 GraphQL 进行集成测试时出现 Jackson 错误
- sql - SQL_ 仅在它们是连续的情况下为每个用户提取失败/恢复事件
- reactjs - 如何在反应中为函数内的状态变量设置值
- macos - 如何在 Mac 中将 Flutter 永久添加到 Path
- assembly - 没有跳过 Asm 注释