开发者

jQuery parent()

开发者 https://www.devze.com 2022-12-30 03:17 出处:网络
jQuery snippet: $开发者_开发知识库(\".sliders dt a\").click(function(){ $(this).parent().parent().parent().find(\".triggers a\").removeClass(\"active\");

jQuery snippet:

$开发者_开发知识库(".sliders dt a").click(function(){
    $(this).parent().parent().parent().find(".triggers a").removeClass("active");
    $(this).toggleClass("active");
    $(this).parent().next("dd").slideToggle("fast");
    return false
});

HTML:

<div class="sliders">
    <div class="triggers">
       <a href="#" class="active">Hide all</a>
    </div>
    <dl>
        <dt>
            <a href="#">text</a>
        </dt>
        <dd>text</dd>
    </dl>
</div>

Three .parent() is used, to catch .triggers block. Is there any way to merge them?


jQuery 1.2.6. version is used, thats why .closest() solutions don't work.


You can use .closest() like this:

$(".sliders dt a").click(function(){
    $(this).closest(".sliders").find(".triggers a").removeClass("active");
    return false
}); 

This goes up to the .sliders div then back down to find the .triggers a beneath.


How does parents() work? It walks up the DOM tree and collects all parents. Than it filters them by the selector specified.

Using jQuery 1.4+ more optimal is to use .closest(). It will work much faster if you have a lot of nodes on your page. Just a thought.

$(this).closest('.sliders').siblings('.triggers').find('a').removeClass(...);


Since .sliders and .triggers are siblings, you need to use .closest() to get .sliders, then traverse over to .triggers, and get its inner a element.

$(".sliders dt a").click(function(){
    $(this).closest('.sliders').prev('.triggers').find("a.active").removeClass("active");
    return false;
});

EDIT:

Question changed, so now answer has changed:

$(".sliders dt a").click(function(){
    $(this).closest('.sliders').find(".triggers a.active").removeClass("active");
    return false;
});
0

精彩评论

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