JavaScript对列表节点的操作:删除指定节点、删除最后一个节点、删除第一个节点、删除所有节点、增加节点
使用菜鸟的运行环境直接测试:http://www.runoob.com/try/try.php?filename=tryjs_events
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script> function removeFirstNode(){ var node = document.getElementsByTagName("li"); document.getElementById("list").removeChild(node[0]); } function removeLastNode(){ var node = document.getElementsByTagName("li"); document.getElementById("list").removeChild(node[node.length-1]); } function addChild(){ var node = document.createElement('li'); node.setAttribute("onclick", "removeElement(this)"); var content = document.getElementById('content').value; var textnode = document.createTextNode(content); node.appendChild(textnode) document.getElementById('list').appendChild(node); } function clearAll(){ document.getElementById("list").innerHTML=''; } function removeElement(_element){ var _parentElement = _element.parentNode; if(_parentElement){ _parentElement.removeChild(_element); } } </script> </head> <body> <input id="content" placeholder="节点内容" value="" /> <button type="button" onclick="removeFirstNode()">删除第一个节点</button> <button type="button" onclick="removeLastNode()">删除最后一个节点</button> <button type="button" onclick="addChild()">增加节点</button> <button type="button" onclick="clearAll()">清除节点</button> <ul id="list"> <li onclick="removeElement(this)">Pretty row 1 </li> <li onclick="removeElement(this)">Pretty row 2 </li> </ul> </body> </html>