简体   繁体   English

jQuery timout函数干扰切换

[英]jQuery timout function interfering with toggling

I have a checkbox that I want to only stay checked for 7 seconds and then uncheck itself. 我有一个复选框,我只想保持选中状态7秒钟,然后取消选中它自己。 I've put together the below code, but despite trying to clear the timeout, it seems to interfere with toggling if the user clicks several times on the toggle. 我整理了以下代码,但是尽管尝试清除超时,但如果用户在切换上单击几次,似乎会干扰切换。

Can anyone help me find a cleaner way to do this that won't mis-behave if the users click too frequently? 谁能帮助我找到一种更干净的方法来执行此操作,如果用户单击频率过高,它不会表现异常?

$('input#foo').on('change', function(){
    clearTimeout(timeout);
    if ( $(this).is(':checked') ) {
        $('#box').addClass('splash').stop();
        $( "div.title" ).html( 'Hide thing' );
        var timeout = setTimeout(function() {
          if ( $('input#foo').is(':checked') ) {
            $('input#foo').prop('checked', false).change();
          }
        }, 7000);
    } 
    else {
        $('#box').removeClass('splash').stop();
        $( "div.title" ).html( 'Reveal thing' );

    }
  });

Remove .change() from this line,and try it. 从此行中删除.change(),然后尝试。 $('input#foo').prop('checked', false); $('input#foo')。prop('checked',false);

I've set it so the action only works 7 seconds after it is clicked, this should solve the mis-behaving 我已对其进行了设置,因此该操作仅在单击后7秒钟内有效,这应该可以解决行为不当

HTML HTML

<input class="checkbox" type="checkbox">I will become unchecked in 7 seconds<br>

jQuery jQuery的

$(".checkbox").click(function() {
  setTimeout(function() {
    $('.checkbox').prop('checked', false);
  }, 7000);
});

Fiddle - 小提琴-

https://jsfiddle.net/8y8zu47p/2/ https://jsfiddle.net/8y8zu47p/2/

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

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