访问元素类到DOM中的位置(jQuery)

时间:2012-10-03 13:57:41

标签: jquery dom loops web

我有以下DOM结构:

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

我想做的是访问&#34; c2&#34;和&#34; c3&#34;相对于当前dom位置的元素。我想循环选择相对于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
..

3 个答案:

答案 0 :(得分:4)

尝试

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

答案 1 :(得分: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
    });
});

答案 2 :(得分:2)

如果li始终是直接父母,您可以使用:

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