删除潜水点击超时

Remove Div On Click With Timeout

本文关键字:超时 水点 潜水 删除      更新时间:2023-12-06

我在点击时有这个javascript来删除点击时的div,但它根本不起作用:(

你能帮帮我吗?我会很高兴(我已经试着搜索其他问题了)

有JS

onclick="setTimeout('$('#wait').remove()', 11000);"

错误的语法和引号用法。此:

onclick = "setTimeout(function() { $('#wait').remove() }, 11000);";

将是正确的。

注意处理程序中嵌套的单引号。结果不会好。浏览器应该对此做什么?
'$('#wait').remove()'

您真的想定义一个函数,并使用来代替。您可以避免将字符串传递给setTimeout()、多级引用等所有陷阱。

function hideit() {
  $('#wait').remove();
}
// ...
<button onclick="setTimeout(hideit, 11000);">click me</button>

我认为几乎所有这些解决方案都能工作。这是你在上面做的另一个可能更优雅的版本,Chymmi。

JsFiddle演示:https://jsfiddle.net/kvvbbz6e/4/


Javascript

$(document).ready(function(){
    //--------------------------------------------------------------
    // this is what you would need
    var waitButton = $('#wait'),
        waitButtonTimer;
    waitButton.on('click',function(){ // clicking this a second time will reset the timer.
        clearInterval(waitButtonTimer);
        waitButtonTimer = setTimeout(function(){
            waitButton.off('click');
            $('.infolabel').text('click event unbound');
        }, 4000);
    });
    //--------------------------------------------------------------
});

HTML

<div id="wait" class="button">Wait Button</div>
<span class="infolabel">Click event bound</span>

CSS

.button {
    display: inline-block;
    color: #666;
    height: 24px;
    font-size: 9.5pt;
    font-weight: bold;
    line-height: 22px;
    border: 0;
    padding: 0 5px;
    margin: 0;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    background: rgb(255,255,255); /* Old browsers */
    background: -moz-linear-gradient(top, rgba(255,255,255,1) 60%, rgba(245,245,245,1) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(60%,rgba(255,255,255,1)), color-stop(100%,rgba(245,245,245,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, rgba(255,255,255,1) 60%,rgba(245,245,245,1) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, rgba(255,255,255,1) 60%,rgba(245,245,245,1) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, rgba(255,255,255,1) 60%,rgba(245,245,245,1) 100%); /* IE10+ */
    background: linear-gradient(to bottom, rgba(255,255,255,1) 60%,rgba(245,245,245,1) 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#f5f5f5',GradientType=0 ); /* IE6-9 */
    box-shadow: 0px 1px 1px #fff;
    cursor: pointer;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}

与其在onclick中内联一些javascript,不如使用jQuery中的.delay.queue

$('#clickme').on('click', function(){
  $('#wait').delay(11000).queue(function(){
    $(this).remove().dequeue()
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wait">Gone in 11 Seconds</div>
<button id="clickme">Click me to start the countdown</button>