my site have many <a target="_blank">
will call api
I need to prevent double click on those button.
here is what I did
.disable {
pointer-events: none;
}
$(document).ready(function(e) {
$('a').click(function(){
$(this).addClass('disable');
setTimeout(function(){
$(this).removeClass('disable');
}, 3000);
});
});
because its target blank, therefor I need those href still able to work after few sec.
Somehow I just not able to enable those button again
The problem is that this
inside setTimeout
is not the same as this
outside it.
You can do something like:
var that = $(this);
that.addClass('disable');
setTimeout(function(){
that.removeClass('disable');
}, 3000);
And then it should work
You could do something like jQuery('.disable').click(function(evt) { evt.preventDefault() })
. This would only stop clicks, though. Tabbing until hitting enter or some other interactions might still trigger a visit.
A "safer" way might be to use JS to temporarily shift the href attribute out and back in later (like storing the original href target somewhere, and replacing with javascript:return false;
or removing the href attribute completely
This is a scoping problem. Inside the setTimeout
, this
no longer refers to the anchor element you're trying to modify; instead it points to the browser window (because setTimeout
is a method on the window
object).
The classic way to solve this is by capturing this
in a separate variable which will still be in scope within the setTimeout
:
$(document).ready(function(e) { $('a').click(function(){ $(this).addClass('disable'); var self = this; setTimeout(function(){ $(self).removeClass('disable'); }, 3000); }); });
.disable {background-color:#F00}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#">test</a>
Or in ES6 you could use a fat arrow function, which doesn't change the variable scope:
$(document).ready(function(e) { $('a').click(function(){ $(this).addClass('disable'); setTimeout(()=>{ $(this).removeClass('disable'); }, 3000); }); });
.disable {background-color:#F00}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#">test</a>
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.