2016-05-05 279 views
3

我想添加更多li元素,如第一個,動態地(即通過按下按鈕)。這裏是jsfiddle動態地將列表元素添加到ul元素

一個沒有工作示例

document.onload = init; 
 
function init(){ 
 
    document.getElementById('add').onclick = add; 
 
} 
 
function add(){ 
 
    var el = document.getElementById('list'); 
 
    var node = document.createElement("li"); 
 
    var link = document.createElement("link"); 
 
    link.setAttribute('href', 'www.google.it'); 
 
    link.setAttribute('name', 'link'); 
 
    node.appendChild(link); 
 
    el.appendChild(node); 
 
}
<ul id="list"> 
 
    <li> 
 
    <a href="www.google.it">link</a> 
 
    </li> 
 
</ul> 
 
<button id="add">Add link</button>

+0

使用'window.onload',而不是'document.onload' ..我不知道什麼時候'document.onload'將被調用... – Rayon

+0

小提琴在這裏... https://jsfiddle.net/rayon_1990/o93ghfc9/3/ – Rayon

回答

1

window.onload = init; 
 
function init(){ 
 
    document.getElementById('add').onclick = add; 
 
} 
 
function add(){ 
 
    var el = document.getElementById('list'); 
 
    var node = document.createElement("li"); 
 
    var link = document.createElement("a"); 
 
    link.setAttribute('href', 'www.google.it'); 
 
    link.innerHTML = "link"; 
 
    node.appendChild(link); 
 
    el.appendChild(node); 
 
}
<ul id="list"> 
 
    <li> 
 
    <a href="www.google.it">link</a> 
 
    </li> 
 
</ul> 
 
<button id="add">Add link</button>