jquery hide all open divs and toggle

与世无争的帅哥 提交于 2019-12-11 04:16:33

问题


I have 2 links and depending on which one they click on want to close all others and show only the information for that link.

Example:

<div class="shipping-container">
    <a href="#" class="ups">Show UPS info</a>
    <a href="#" class="fedex">Show Fedex info</a>
    <div class="ups info" style="display:none">the info for ups</div>
    <div class="fedex info" style="display:none">the info for fedex</div>
</div>

Any ideas how I can do this with Jquery toggle for clicking one of the links and hide all others if there open. I only want to show info for one shipping method at a time. Also I would like an option for the user to click showall and all of them are displayed, if possible. Thanks in advance....


回答1:


$(".shipping-container a").click(function() {
    $("div.info").hide();
    $("div." + this.className).show();
});

You can try it here.




回答2:


$(".shipping-container > a.ups").click(function() {
    $(".shipping-container > .info").hide();
    $(".shipping-container > .ups.info").show();
    return false;
});
$(".shipping-container > a.fedex").click(function() {
    $(".shipping-container > .info").hide();
    $(".shipping-container > .fedex.info").show();
    return false;
});
$(".shipping-container > a.showall").click(function() {
    $(".shipping-container > .info").show();
    return false;
});

Or, if you wanted shiny animations (and the ability to easily add more shipping types):

["ups", "fedex"].forEach(function(method) {
    $(".shipping-container > a."+method).click(function() {
        $(".shipping-container > .info:not(."+method+")").slideUp("slow");
        $(".shipping-container > ."+method+".info").slideDown("slow");
        return false;
    });
});
$(".shipping-container > a.showall").click(function() {
    $(".shipping-container > .info").slideDown("slow");
    return false;
});

A slightly modified example is here.




回答3:


Almost same as above

$(".shipping-container a").click(function() {
    $("div.info").hide().filter("div." + this.className).show();
});

I dont know if this is more efficient than reselecting the div... it might be.

Also, if the html is the actual one, you might want to use methods like siblings for instance:

$(".shipping-container a").click(function() {
    $(this).siblings("div.info").hide().filter("div." + this.className).show();
});

I think it's quicker.



来源:https://stackoverflow.com/questions/4910177/jquery-hide-all-open-divs-and-toggle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!