我有一些简单的代码行,并且无法理解为什么.insertBefore
每四次点击都不起作用。
<ul id="container">
<li>1
<li>2
<li>3
</ul>
<button id="button">change</button>
var button = document.getElementById('button');
button.addEventListener('click', changeIt, false);
function changeIt(){
// alert('hi'); (checked that function is running 4th time)
var container = document.getElementById('container');
var first = container.firstChild;
var last = container.lastChild;
container.insertBefore(last, first);
// alert(last); >> shows last item is a text node every 4th time
}
答案 0 :(得分:1)
我明白了! 第四次,insertBefore没有替换HTML元素,而是替换文本对象。
我将确保测试变量是否是带有nodeType的HTML元素,如下所示:
// if it's an html element, the nodeType must be 1
// if it's not
if(last.nodeType !== 1){
// remove it,
last.remove();
// again grab last item
last = container.lastChild;
}