首页 > 解决方案 > 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>

标签: javascripthtml

解决方案


这是一个带有添加项按钮的示例,基本上您会听到单击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>


推荐阅读