简体   繁体   中英

Howto cancel a delayed DOM element removal

I am trying to remove a DOM element after a delay. I also wish to cancel this removal with a user click (if they click before the timer expires. This is what I have:

<div class="delete">Delete me!</div>

Obviously, I am only showing the relevant source.

$("div.delete").click(function() {
    var element = $(this),
        timeout = element.attr('data-timeout');
    if (timeout) {
        clearTimeout(timeout);
        element.removeAttr('data-timeout');
        element.text("Delete me!");
    } else {
        timeout = setTimeout(function() {
            element.remove();
            alert('Sniff, too late!');
        }, 2000);
        element.attr('data-timeout', timeout);
        element.text("Save me!");
    }
});

This works! My questions

  1. Is there a better way? My first failed try had mutiple handlers.
  2. Why doesn't it work in Javascript 1.7?

http://jsfiddle.net/zhon/H8a9J/

It doesn't work with JavaScript 1.7 because the browser you are using doesn't support it and/or or the way how it's embedded. Your fiddle works fine with Firefox.

http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28ECMAScript%29

You need to define timeout outside of your handler.

var timeout;
$("div.delete").click(function() {
    var element = $(this);
    if (timeout) {
        clearTimeout(timeout);
        timeout = undefined;
        element.text("Delete me!");
    } else {
        timeout = setTimeout(function() {
            element.remove();
            alert('Sniff, too late!');
        }, 2000);
        element.text("Save me!");
    }
});

I'd recommend enclosing the code to add handlers within some other function to avoid muddying the global namespace with timeout ids.

使timeout成为全局,并在用户单击时清除它。

clearTimeout(timeout);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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