0

我有一个脚本,我在单击按钮后将其禁用 5 秒钟,然后再次启用它。

$(document).on('click', 'button', function () {
    var htmls = $(this).html();
    $(this).prop("disabled", true);
    setTimeout(function () {
        $(this).prop("disabled", false);
        $(this).html(htmls);
    }, 5000);
    $(this).html('<img src="<?=CDN(' / icons / loading / loading5.gif ')?>" />');
});

不知何故,setTimeout不会结束,所以按钮不会再次启用。我没有收到任何错误消息。

4

2 回答 2

4

Save $(this) into variable before setTimeout call, since this keyword inside setTimeout handler refers to window object:

$(document).on("click", "button", function() {
    var $this = $(this),
        htmls = $this.html();

    $this.prop("disabled", true)
         .html('<img src="..." />');

    setTimeout(function() {
       $this.prop("disabled", false)
            .html(htmls);
    }, 5000);
});
于 2013-03-25T10:39:03.193 回答
2

这里没有引用 DOM 元素。尝试放入另一个 temarory 变量。因为它在外面setTimeOut

 var $this = $(this),
        htmls = $this.html();

    $this.prop("disabled", true);
    setTimeout(function() {
       $this.prop("disabled", false).html(htmls);
    }, 5000);
于 2013-03-25T10:40:43.543 回答