简体   繁体   English

jQuery重置切换状态?

[英]jQuery reset toggle state?

I'm using toggle on a button like so: 我正在使用像这样的按钮toggle

$('#button123').toggle(function() {
        $("#button123").text("-");

        $("#slideDiv").slideDown( "fast", function() {

        });
}, function() {
        $("#button123").text("+");

        $("#slideDiv").slideUp( "fast", function() {

        });
});

Further down in my code I want to "reset" the toggle state. 在我的代码中,我想进一步“重置”切换状态。 and make slideDiv slide back up. 并使slideDiv滑动。

Currently I am trying to do that by: 目前,我正在尝试通过以下方式做到这一点:

    $("#button123").text("+");

    $("#slideDiv").slideUp("fast", function() {
        // Animation complete.
    });

The problem is that after running that code I have to press button123 twice for the toggle to work again. 问题是运行该代码后,我必须按两次button123才能使切换再次起作用。 I'm assuming this is because I somehow need to reset it? 我假设这是因为我需要重新设置它吗?

Any ideas? 有任何想法吗?

The toggle function uses an internal mechanism to determine which of the 2 callbacks to be executed. 切换功能使用内部机制来确定要执行2个回调中的哪一个。 So assuming it is an incremental counter where if the value if the value is odd then the first callback else the second callback is executed, when you update the text and display of the elements outside of the toggle handlers the internal counter is not executed. 因此,假设它是一个增量计数器,如果该值的值是奇数,则执行第一个回调,否则执行第二个回调,当您更新文本并在切换处理程序之外显示元素时,将不执行内部计数器。 So toggle does not know about the fact that the text is changed to + which will result in toggle calling the second handler(if in the previous click handler one was executed). 因此, toggle不知道将文本更改为+会导致切换调用第二个处理程序(如果在上一个单击处理程序中已执行)的事实。

One possible solution is to use a click based solution instead of toggle(another reason is toggle was removed in 1.9) 一种可能的解决方案是使用基于单击的解决方案而不是切换(另一个原因是在1.9中删除了切换)

$('#button123').click(function () {
    var text = $.trim($(this).text());
    $(this).text(text == "-" ? '+' : '-');
    if (text == '-') {
        $("#slideDiv").slideUp("fast", function () {});
    } else {
        $("#slideDiv").slideDown("fast", function () {});
    }
});

Demo: Fiddle 演示: 小提琴

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

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