简体   繁体   English

关闭Javascript切换

[英]Close Javascript Toggle

The following code is working to open data toggles on my site: 以下代码正在打开我网站上的数据切换:

$(window).load(function(){
    $("a[data-toggle]").on("click", function(e) {
        e.preventDefault();  // prevent navigating
        var selector = $(this).data("toggle");  // get corresponding element
        $("article").hide();
        $(selector).show();
    });
});

And following is the HTML: 以下是HTML:

<a href="#" data-toggle="#uniquediv">Toggle</a>
<article id="uniquediv">
    Content in Toggle
</article>

I am trying to see what I need to change to allow the toggle to close when the link is clicked as well. 我试图查看要更改的内容,以便在单击链接时也可以关闭切换开关。 Also it would be nice if another toggle is opened, then the open one will close so that only one stays open at a time. 如果打开另一个开关,那会很好,然后打开的开关将关闭,这样一次只能保持打开状态。

Any help would be appreciated. 任何帮助,将不胜感激。

You can do something like this: 您可以执行以下操作:

$("a[data-toggle]").on("click", function(e) {
e.preventDefault();  // prevent navigating
var selector = $(this).data("toggle");  // get corresponding element
if($(selector).is(":visible")) {
    $(selector).hide();
}

    else {
        $('article').hide();
        $(selector).show();

    }



});

Demo: http://jsfiddle.net/2bkhwhba/ 演示: http//jsfiddle.net/2bkhwhba/

Not sure about your CSS settings, but i made it like this: 不确定您的CSS设置,但是我这样做是这样的:

a {
    display:block;
}

article {
    display:none;
}

Explanation, if needed - you have to check if element is visible, or not, on click, and consequently - show/hide it... 说明,如果需要-您必须在单击时检查元素是否可见,因此-显示/隐藏它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM