<script type="text/javascript">
window.onload=function ()
{
var oBtn=document.getElementById('btn1');
var oTxt=document.getElementById('txt1');
var oUl=document.getElementById('ul1');
oBtn.onclick=function()
{
var oLi=document.createElement('li');
var aLi=document.getElementsByTagName('li');
oLi.innerHTML=oTxt.value;
if(aLi.length==0)//ul中没有li,需要先添加子节点
{
oUl.appendChild(oLi);
}
else
{
oUl.insertBefore(oLi,aLi[0]);
}
}
}
</script>
</head>
<body>
<input id="txt1" type="text"/>
<input id="btn1" type="button" value="创建li"/>
<ul id="ul1">
</ul>
</body>
- appendChild()接收一个参数,为创建之后的<li> 名称
- childBefore()接收两个参数,为创建之后的<li> 名称和插入在第几个<li>之前的位置。
注意:当<ul>中 无<li>时,需要先用appendChild()给原来的li添加子节点后才能在新创建的li之前添加元素。