2010-05-28 23 views
7

为什么the following code失败:jQuery的.parent()不工作

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 />"); 
}); 

回答

16

class_a_jquery_objects [0]是一个DOM元素,而不是一个jQuery对象。你不能用它调用jQuery方法。首先,您需要将它包装在一个jQuery对象:

$(class_a_jquery_objects[0]).parent() 
+1

class_a_jquery_objects.eq(0).parent()应藏汉工作。 – jAndy 2010-05-28 07:15:32

+0

非常感谢您的及时答复! – 2010-05-28 07:18:04

1

您需要使用jQuery对象来包装它

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