问题
I want to make it so that this button can be clicked only once. If someone clicks it more times then the function will not be performed. How can I do that?
$(".btn_ranking").click(function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
})
});
回答1:
Use one()
to attach the event handler:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
回答2:
In addition to Rory's answer, you can also do one of these:
I can't tell from your code here what your markup is, but if your .btn_ranking
element is a <button />
tag, then in your click function you can also add a disabled
attribute to the button, which should prevent it from being clicked again.
https://www.w3schools.com/tags/att_button_disabled.asp
Another thing you can do is add an inline style to that same element of pointer-events: none;
A caveat for ALL of these solutions is that they can be circumvented by simply refreshing the browser.
来源:https://stackoverflow.com/questions/51403168/jquery-click-only-once