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
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.