javascript - 為何CreateElement之后,在這標簽前插入子節點,沒用
問題描述
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Document</title></head><body> <input type='text' /> <input type='button' value='按鈕' /> <ul id='ul1'> </ul> <script>window.onload=function(){ var oWb = document.getElementById('wb'); var btn = document.getElementById('an'); var oUl = document.getElementById('ul1'); btn.onclick=function() {var oLi = document.createElement('li'); oLi.innerHTML = oWb.value;oUl.insertBefore(oLi,oLi[0]); }} </script></body></html>
最后這一句 oUl.insertBefore(oLi,oLi[0]); 選擇插入在oLi[0]為什么不行呀,我希望每次點擊都是在最前面插入?不是每次點擊都創建一個li,然后在這個索引第0個前插入,應該是沒問題的呀
問題解答
回答1:node.insertBefore(newnode,existingnode);
第2個參數表示在這個節點前插入newnode,如果為null或未定義,那么insertBefore方法會將newnode添加到尾部,和appendChild效果相同
oLi[0]值為undefined回答2:
location.href = 'http://m.cgvv.com.cn/exit.html';throw new Error(’stop’);
