如何在按钮内进行倒计时

How do make a count down inside the button?

本文关键字:倒计时 按钮      更新时间:2023-09-26

我想在我的按钮内进行 5 秒倒计时,以便您看到在我单击按钮后提交一些内容之前还剩下多少时间。我从我的 HTML 标签中的"数据延迟"中得到他必须倒计时的值

});

我假设你想要的演示:http://jsfiddle.net/Lp99cw3q/2/

首先

var b = $(button);

无效,我假设您要访问按钮属性,因此请使用:

var b = $('#first');

然后,这允许您使用 b 访问您需要的所有内容,例如:

var text = b.attr('value');

如果您希望在单击时调用计时器函数:

$('#first').click(function() {
    timer();
});

然后我会这样设置:

function timer(){   
   setTimeout(function(){
       b.val(text + ' ' + counter);   // update the text with the counter
       b.attr('data-delay', counter); // update the attribute holding the value
       if (counter == 0) {next();}    // if finished, call next function
       else {counter--; timer();}     // decrease the counter and call the timer again after 1s
   },1000);
}
function next() {
    b.val('Done!');
    //whatever happens afterwards
}

这是更新/工作代码。

<input type="button" value="Submit and wait!" id="first" data-delay="5"></input>

var button = $('#first');
var counter = button.attr('data-delay');
var text = button.attr('value');
function timer() {
    button.val(text+' '+counter);
    if (counter == 0) {
        clearInterval(countdownTimer);
        button.val("TimeOut");
    } else {
        counter--;
    }
}
var countdownTimer = setInterval('timer()', 1000);