jQuery .parent() does not work

人走茶凉 提交于 2019-12-06 22:05:49

问题


Why the following code fails with:

Error: class_a_jquery_objects[0].parent is not a function

?

HTML:

<div>
    <div class='a b'></div>
    <div class='b c'></div>
    <div class='c a'></div>
</div>    
<div id='log'></div>

JS:

$(function() {
    var class_a_jquery_objects = $(".a");

    $("#log").append(class_a_jquery_objects.length + "<br />");
    $("#log").append(class_a_jquery_objects[0] + "<br />");
    $("#log").append(class_a_jquery_objects[0].parent() + "<br />");
});

回答1:


class_a_jquery_objects[0] is a DOM element and not a jQuery object. You can't call jQuery methods with it. You need to first wrap it in a jQuery object:

$(class_a_jquery_objects[0]).parent()



回答2:


You need to wrap it with JQuery object

   $("#log").append($(class_a_jquery_objects[0]).parent() + "<br />");


来源:https://stackoverflow.com/questions/2927225/jquery-parent-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!