2012-10-03 42 views
0

我有以下的DOM結構:訪問的元素類您在DOM(jQuery的)是在哪裏

<div id="cont"> 
<ul> 
    <li> 
     <span class="c1"><span class="c2">...</span><span class="c3">...</span></span> 
    </li> 
    <li> 
     <span class="c1"><span class="c2">...</span><span class="c3">...</span></span> 
    </li> 
    <li> 
     <span class="c1"><span class="c2">...</span><span class="c3">...</span></span> 
    </li> 
    ... 
    <li> 
     <span class="c1"><span class="c2">...</span><span class="c3">...</span></span> 
    </li> 
</ul> 
</div> 

有以下的jQuery:

$("#cont ul li").each(function (e) { 
    $(this).bind("mousemove",function(d) { 
     var ele = $(this + " .c2"); 
     var ele2 = $(this " .c3"); 
     //do stuff 
    }); 
}); 

我想do是訪問相對於當前dom位置的「c2」和「c3」元素。我想循環選擇以下相對於DOM的頂部:

ele = $("#cont ul li span .c2"); 
ele = $("#cont ul li span .c3"); 
//Do Stuff 
//Move to the next set of Li's 
ele = $("#cont ul li span .c2"); 
ele = $("#cont ul li span .c3"); 
//Do Stuff 
//Move to the next set of Li's 
ele = $("#cont ul li span .c2"); 
ele = $("#cont ul li span .c3"); 
//Do Stuff 
//Move to the next set of Li's 
.. 
+0

介意我問什麼 「'//完成Stuff'」 呢?你甚至可能不需要'.each()'循環... – nbrooks

+0

做的東西是否與跨度中的圖像大小計算。每個圖像都是不同的大小。它很重要。我在這裏使用了例子,我的代碼工作。全力讚揚! – user974896

回答

4

使用.find()選擇當前匹配元素的後裔。

$("#cont ul li").each(function (e) { 
    $(this).bind("mousemove",function(d) { 
     var ele = $(this).find(".c2"); 
     var ele2 = $(this).find(".c3"); 
     //do stuff 
    }); 
}); 
4

嘗試

$("#cont ul li").each(function (e) { 
    $(this).bind("mousemove",function(d) { 
    var ele = $(this).find(".c2"); 
    var ele2 = $(this).find(".c3"); 
    //do stuff 
}); 
}); 
2

如果李總是會立即家長,您可以使用:

var elem, elem2; 
$('.c1').bind("mousemove",function(d) { 
    elem=$(this).parent().find('.c2'); 
    elem2=$(this).parent().find('.c2'); 
    //Do stuff 
})