JS DOM追加子项不起作用
JS DOM append child does not work
我正在尝试实现一个简单的函数,该函数获取一些元素列表(在本例中,我传递一些<li>
元素),并将它们按随机顺序附加到某个父节点(<ul>
)。为了做到这一点,我写了这样的东西:
console.log(tmpList);
var maxIndex = tmpList.length;
while(tmpList.length > 0) {
var curIndex = Math.floor(Math.random() * maxIndex);
if(tmpList[curIndex] && tmpList[curIndex].nodeType===1) {
var elem = tmpList.splice(curIndex, 1);
console.log(elem);
parent.appendChild(elem);
}
}
正如你所看到的,我确实检查了随机选择的索引是否真的仍然存在于tmpList
中,以及它是否真的是html元素。然而,当我运行此代码时,我得到:
[li, li, li, li]
[li]
NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
我做错了什么?
ps。请不要给我诸如"使用jquery"或"使用innerHTML连接它"之类的建议,因为我不能使用它们是有原因的。
[edit]parent
元素是在几行之前定义的,所以情况并非如此。
更新
我根据一个答案做了一些更改,所以代码看起来如下:
while(tmpList.length > 0) {
var curIndex = Math.floor(Math.random() * tmpList.length);
var elem = tmpList.splice(curIndex, 1);
console.log(elem);
if(elem instanceof HTMLElement) {
//console.log(curIndex);
console.log(elem);
parent.appendChild(elem);
}
}
return true;
现在它看起来好了一点,但仍然很奇怪。现在控制台输出为:
[li, li, li, li]
[li]
[li]
[li]
[li]
所以它有li元素,但不将它们视为HTMLNode…:o(与我使用elem !== null && elem !== undefined && elem.nodeType === 1
时的结果相同)
您在while
之前声明了maxIndex
,在while
中更改了数组,因此我建议您更改:
var curIndex = Math.floor(Math.random() * maxIndex);
到(这将确保curIndex始终小于tmpList.lenght)
var curIndex = Math.floor(Math.random() * tmpList.length);
然后拼接你的数组并验证你的元素:(为了更好地验证,你应该检查你的elem
是否是html元素)
while(tmpList.length > 0) {
var curIndex = Math.floor(Math.random() * tmpList.length);
if (curIndex < tmpList.lenght){
var elem = tmpList.splice(curIndex, 1);
// array.splice returns array of removed from array elements, so you need work with first element in that array.
if (elem[0] instanceof HTMLElement && elem[0].nodeType === 1){
//Add to parent:
parent.appendChild(elem[0]);
}
}
}
您没有名为parent
的元素
好的,我发现了问题。诀窍是elem持有包含一个匹配元素的列表。解决方案是使用CCD_ 11。
相关文章:
- 追加Jquery后的Binding Click事件不起作用
- jquery 1.7追加后点击事件不起作用
- 单击事件不起作用后追加 - AngularJS
- 动态追加表行时,列切换不起作用
- jQuery追加函数在IE8中不起作用
- 将查询选择器保存在要追加的变量中不起作用
- 在上下文菜单上,在 HTML 表中追加行时不起作用
- 在 Java 脚本中使用追加时 HTML 标记不起作用,但在执行硬编码时 html 代码工作正常
- 追加 jquery 不起作用
- 额外追加后点击功能不起作用
- function(){如果淡出,则追加}不起作用
- Jquery:动态追加到context.childNodes[4]不起作用
- 单击时克隆和追加会使多个元素和切换不起作用
- 来自数组的 IE 追加子项不起作用
- Ajax 函数在 JQuery 追加中调用时不起作用
- 从追加中选择 2 不起作用
- 事件在追加视图中不起作用
- 剑道工具栏追加不起作用
- 在 jQuery 中回调追加后,锚点不起作用
- jquery追加不起作用