我在启用按钮之前使用以下代码进行倒计时。
<script type="text/javascript">
$.fn.timedDisable = function(time) {
if (time == null) { time = 5000; }
return $(this).each(function() {
$(this).attr('disabled', 'disabled');
var disabledElem = $(this);
setTimeout(function() {
disabledElem.removeAttr('disabled');
}, time);
});
};
$(function() {
$('#btnContinue').timedDisable();
});
</script>
如何让按钮值读取值=“Continue(x)”, 其中x是启用之前剩余的秒数,之后它只是值=“继续”?
答案 0 :(得分:3)
这个怎么样:
示例: http://jsfiddle.net/mgSVX/2/ 编辑: (更新示例以使用请求的文字值)
$.fn.timedDisable = function(time) {
if (time == null) {
time = 5000;
}
var seconds = Math.ceil(time / 1000); // Calculate the number of seconds
return $(this).each(function() {
$(this).attr('disabled', 'disabled');
var disabledElem = $(this);
var originalText = this.innerHTML; // Remember the original text content
// append the number of seconds to the text
disabledElem.text( originalText + ' (' + seconds + ')');
// do a set interval, using an interval of 1000 milliseconds
// and clear it after the number of seconds counts down to 0
var interval = setInterval(function() {
// decrement the seconds and update the text
disabledElem.text( originalText + ' (' + seconds + ')');
if (seconds === 0) { // once seconds is 0...
disabledElem.removeAttr('disabled')
.text(originalText); //reset to original text
clearInterval(interval); // clear interval
}
}, 1000);
});
};
$(function() {
$('#btnContinue').timedDisable();
});
答案 1 :(得分:0)
@ user113716的答案几乎正常,但我认为缺少1行代码,因此无法正常工作。所以我修改了他的代码如下: (实际上我只是在他的代码中加了1行)
$.fn.timedDisable = function(time) {
if (time == null) {
time = 5;
}
var seconds = Math.ceil(time); // Calculate the number of seconds
return $(this).each(function() {
$(this).attr('disabled', 'disabled');
var disabledElem = $(this);
var originalText = this.innerHTML; // Remember the original text content
// append the number of seconds to the text
disabledElem.text(originalText + ' (' + seconds + ')');
// do a set interval, using an interval of 1000 milliseconds
// and clear it after the number of seconds counts down to 0
var interval = setInterval(function() {
seconds = seconds - 1;
// decrement the seconds and update the text
disabledElem.text(originalText + ' (' + seconds + ')');
if (seconds === 0) { // once seconds is 0...
disabledElem.removeAttr('disabled')
.text(originalText); //reset to original text
clearInterval(interval); // clear interval
}
}, 1000);
});
};
$(function() {
$('#btnContinue').timedDisable(20);
});
我在他的代码中添加了这一行:
seconds = seconds - 1;
我也删除了&#34; 1000&#34;进行第二次计算,因为我们输入&#34; 10&#34;相反&#34; 10000&#34;几秒钟以避免打字错误并计算错误。
希望它有所帮助。