开发者

Is there a better way to select an element which is not a sibling of the interacted one?

You could find a demonstration of my idea at this fiddle:

http://jsfiddle.net/Hwdfz/7/

HTML:

<div class="div1">
    <div class="div2">
        Div2
    </div>
    <div class="div3">
        <div class="div4">
            <a href="#">Div4</a>
    开发者_C百科    </div>
    </div>
</div>
<div class="div1">
    <div class="div2">
        Div2
    </div>
    <div class="div3">
        <div class="div4">
            <a href="#">Div4</a>
        </div>
    </div>
</div>

JavaScript:

$('.div3 a').each(function(){
    $(this).bind('click',function(){
        $(this).parents('.div1').find('.div2').css('background','#FF0000');    
    });
});

I don't think reaching it's parent is not very effective. Do you have any suggestions?


Use .closest [docs]:

Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

$('.div3 a').click(function(){
    $(this).closest('.div1').find('.div2').css('background','#FF0000');    
});

If you are sure about the structure, you could also go back to .div3 only and select its siblings:

$(this).closest('.div3').siblings('.div2').css('background','#FF0000');    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜