javascript 收到错误:无法在“节点”上执行“appendChild”:参数 1 的类型不是“节点”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28978457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting an error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
提问by PanicBus
I've seen people with this problem before here but none of the answers helped me understand my issue better.
我之前在这里见过有这个问题的人,但没有一个答案能帮助我更好地理解我的问题。
I have a sorting function that isn't sorting elements attached to the DOM, but giving an error in the console: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
我有一个排序功能,它不是对附加到 DOM 的元素进行排序,而是在控制台中给出错误: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
I don't understand why beyond the fact that it can't append the objects to the DOM because they're of different types.
我不明白为什么除了它不能将对象附加到 DOM 之外,因为它们是不同的类型。
function sorting(){
$('#sort_by a').click(function(e){
var sortAttr = $(this).attr('href').slice(1);
e.preventDefault()
var bands = $('#results').children();
bands.sort(function (a, b) {
if ($(a).attr(sortAttr) > $(b).attr(sortAttr)){
return 1;
}
if ($(b).attr(sortAttr) > $(a).attr(sortAttr)){
return -1;
}
return 0;
});
var appendAnim = function(items, index){
$(items[index]).hide();
$(items[index]).fadeIn(500);
document.getElementById('results').appendChild(items[index])
if(index < items.length ){
appendAnim(items,index + 1);
}
}
appendAnim(bands,0)
return false;
});
};
采纳答案by WorldFS
You are mixing up jQuery DOM object and native javascript DOM object.
您正在混淆 jQuery DOM 对象和本机 javascript DOM 对象。
The DOM object returns by jQuery selector (and $('#results').children() in your case) is a object created by jQuery, which is different from javascript DOM objects. Hence, you can not use it in native javascript method .appendChild(Node)
由 jQuery 选择器返回的 DOM 对象(在您的情况下为 $('#results').children() )是由 jQuery 创建的对象,它与 javascript DOM 对象不同。因此,您不能在原生 javascript 方法 .appendChild(Node) 中使用它
Since you're using jQuery I would suggest you to use .append() method, so change this
由于您使用的是 jQuery,我建议您使用 .append() 方法,因此请更改此
document.getElementById('results').appendChild(items[index])
to this:
对此:
$("#results").append(items[index])