javascript 为什么调用 jQuery 的 appendChild 会因未定义错误而失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23403105/
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
Why does call to jQuery's appendChild fail with undefined error?
提问by Saqib Ali
Here is my simple HTML:
这是我的简单 HTML:
<body>
<div id="myParentDivElement">
Hello World!
</div>
</body>
Here is the accompanying JavaScript:
这是随附的 JavaScript:
$(document).ready(function() {
var myDOMElement = document.getElementById("myParentDivElement");
var newDivID = "div_1";
var newDiv = $('<div id="' + newDivID + '"/>');
$( newDiv ).css('marginLeft', '50px');
var newSpanID = "span_1";
var newSpan = $('<span id="' + newSpanID + '"/>');
newSpan.text('myLabel');
newDiv.appendChild(newSpan);
$( myDOMElement ).appendChild(newDiv);
});
But when I run this code the line newDiv.appendChild(newSpan);
gives the following error:
但是当我运行此代码时,该行newDiv.appendChild(newSpan);
出现以下错误:
Uncaught TypeError: undefined is not a function
Can someone explain why? Here is the JSFiddle showing that it doesn't work: http://jsfiddle.net/TsTMx/2/
有人可以解释为什么吗?这是 JSFiddle 显示它不起作用:http: //jsfiddle.net/TsTMx/2/
回答by MrCode
.appendChild()
is a plain JavaScript method, not jQuery. The jQuery method is .append()
.
.appendChild()
是一个普通的 JavaScript 方法,而不是 jQuery。jQuery 方法是.append()
.
newDiv.append(newSpan);
$( myDOMElement ).append(newDiv);
回答by Tushar Gupta - curioustushar
Use .append()
利用 .append()
newDiv.append(newSpan);
.appendChild()works with DOM element. newDiv
is jQuery Object not a plain JavaScript DOM element.
.appendChild()适用于 DOM 元素。newDiv
是 jQuery Object 不是普通的 JavaScript DOM 元素。
回答by Quentin
newDiv
is a jQuery object, not a DOM object.
newDiv
是一个 jQuery 对象,而不是一个 DOM 对象。
jQuery objects do not have an appendChild
method, they have an append
method.
jQuery的对象没有一个appendChild
方法,他们的append
方法。