为什么调用jQuery的appendChild会因未定义的错误而失败? [英] Why does call to jQuery's appendChild fail with undefined error?

查看:171
本文介绍了为什么调用jQuery的appendChild会因未定义的错误而失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的简单HTML:

Here is my simple HTML:

<body>
    <div id="myParentDivElement">
        Hello World!
    </div>
</body>

这是随附的JavaScript:

Here is the accompanying 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);
});

但是当我运行此代码时,行 newDiv.appendChild(newSpan); 给出以下错误:

But when I run this code the line newDiv.appendChild(newSpan); gives the following error:

Uncaught TypeError: undefined is not a function 

有人可以解释原因吗?
这是JSFiddle显示它不起作用: http://jsfiddle.net/TsTMx/ 2 /

Can someone explain why? Here is the JSFiddle showing that it doesn't work: http://jsfiddle.net/TsTMx/2/

推荐答案

.appendChild()是一个纯JavaScript方法,而不是jQuery。 jQuery方法是 .append()

.appendChild() is a plain JavaScript method, not jQuery. The jQuery method is .append().

newDiv.append(newSpan);   
$( myDOMElement ).append(newDiv);

这篇关于为什么调用jQuery的appendChild会因未定义的错误而失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆