Javascript jQuery setTimeout() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30107010/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:40:30  来源:igfitidea点击:

jQuery setTimeout() Function

javascriptjquery

提问by ARTLoe

I am new to JS and facing some challenges which may seem simple.

我是 JS 新手,面临一些看似简单的挑战。

what i want to do is:

我想做的是:

  1. a user clicks on a button that states 'submit'
  2. when the button is clicked the word 'submit' changes to 'please wait...' & button is disabled
  3. the button is disabled for 2 seconds
  4. after 2 seconds the word 'please submit..' changes back to 'submit' & the button becomes activated (its no longer disabled)
  1. 用户点击一个显示“提交”的按钮
  2. 单击按钮时,“提交”一词会更改为“请稍候...”& 按钮被禁用
  3. 按钮禁用 2 秒
  4. 2 秒后,“请提交..”一词变回“提交”,按钮变为激活状态(不再禁用)

i have written the below code. Any advise on this would be much appreciated

我写了下面的代码。对此的任何建议将不胜感激

html

html

<form action="#" method="post">
    <input type="button" name="submit" value="Submit" class="submit_wide" id="myBtn" >
</form>

javascript

javascript

$(".submit_wide").click(function () {
    $(this).val('Please wait..');
    $(this).attr('disabled', true);
    setTimeout(function() { 
        $(this).attr('disabled', false);
        $(this).val('Submit');
    }, 2000);
});

回答by Dave

The problem is that inside the setTimeout()call, thisdoesn't refer to the button. You need to set a variable to keep the reference to the button.

问题是在setTimeout()调用内部,this没有引用按钮。您需要设置一个变量来保持对按钮的引用。

I've created a sample below. See how I use the variable named $this.

我在下面创建了一个示例。看看我如何使用名为$this.

$(".submit_wide").click(function () {
    var $this = $(this);
    $this.val('Please wait..');
    $this.attr('disabled', true);
    setTimeout(function() { 
        $this.attr('disabled', false);
        $this.val('Submit');
    }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" class="submit_wide" value="Submit"/>