<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li></ul>
<p id="demo">请点击按钮向列表插入一个项目。</p>
<button onclick="myFunction()">试一下</button>
<script>
function myFunction()
{
var newItem=document.createElement("LI")
var textnode=document.createTextNode("Water")
newItem.appendChild(textnode)
var list=document.getElementById("myList")
list.insertBefore(newItem,list.childNodes[0]);
}
</script>
<p><b>注释:</b><br>首先请创建一个 LI 节点,<br>然后创建一个文本节点,<br>然后向这个 LI 节点追加文本节点。<br>最后在列表中的首个子节点之前插入此 LI 节点。</p>
</body>
</html>
document.getElementById("myList").insertBefore(newItem,existingItem);
jquery中的:
$("button").click(function(){
$("<span>Hello world!</span>").insertBefore("p");
});
本文介绍了一种利用JavaScript来动态地向HTML列表中插入新项的方法。通过创建新的LI元素,并将文本节点附加到该元素上,最终将LI元素插入到指定位置。此外,还展示了如何使用jQuery实现类似的功能。
1273

被折叠的 条评论
为什么被折叠?



