jQuery 单击后如何使按钮无法单击?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5830781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make button unclickable after it is being clicked?
提问by good_evening
I want that after my button is clicked, it would be unclickable for a few seconds, how can I do it? I want to write a code for all buttons, not just for a one. So, I need something like that:
我希望在我的按钮被点击后,它会在几秒钟内无法点击,我该怎么做?我想为所有按钮编写代码,而不仅仅是为一个按钮编写代码。所以,我需要这样的东西:
$(document).ready(function() {
$('input[type="button"]').click(function() {
$(this).css("hidden: true");
delay(3);
$(this).css("hidden: normal");
})
})
It is just a pseudo-code, could you give me a hand?
这只是一个伪代码,你能帮我一把吗?
回答by alex
With jQuery...
用jQuery...
$(document).ready(function() {
$('input[type="button"]').click(function() {
var input = this;
input.disabled = true;
setTimeout(function() {
input.disabled = false;
}, 3000);
});
});
Without jQuery...
没有jQuery...
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('input[type="button"]')
.addEventListener('click', (e) => {
let input = e.target;
input.disabled = true;
setTimeout(function() {
input.disabled = false;
}, 3000);
});
});
Alternatively capture the clicks on a persistent ancestor element and check if they're input[type="button"]
types. This prevents attaching multiple events for each element.
或者,捕获对持久祖先元素的点击并检查它们是否是input[type="button"]
类型。这可以防止为每个元素附加多个事件。
回答by Jon
Disabling an element is done by adding the disabled
attribute, giving it the value disabled
. Enabling it again is done by removing the attribute.
禁用元素是通过添加disabled
属性来完成的,给它值disabled
。再次启用它是通过删除该属性来完成的。
Update:Fixed the answer by using setTimeout
-- sorry for the confusion with $.delay
.
更新:通过使用修复了答案setTimeout
- 抱歉与$.delay
.
$(document).ready(function() {
$('input[type="button"]').click(function() {
var el = $(this);
el.attr('disabled', 'disabled');
setTimeout(function() { el.removeAttr('disabled'); }, 3000);
})
})
回答by Marwelln
Add the disabled attribute.
添加禁用属性。
$(this).attr('disabled', true);
回答by netbrain
This should do it.
这应该这样做。
$(document).ready(function() {
$('input[type="button"]').click(function() {
$(this).hide().delay(3000).show();
})
})
回答by ezmilhouse
Fiddle here: http://jsfiddle.net/ezmilhouse/Hw6Gf/1/
在这里小提琴:http: //jsfiddle.net/ezmilhouse/Hw6Gf/1/
$(document).ready(function() {
$('input[type="button"]').click(function() {
$(this).attr('disabled','disabled');
setTimeout(function() {
$('input[type="button"]').removeAttr('disabled');
}, 3000);
});
});