gpt4 book ai didi

计算不起作用后javascript按钮禁用和启用

转载 作者:行者123 更新时间:2023-11-30 16:34:34 25 4
gpt4 key购买 nike

我的代码如下。当我单击搜索按钮时,它会进入一个打印 5000 次“hi”的 for 循环。在计算开始之前,我想禁用该按钮。 console.log 完成后,我想重新启用此按钮。但由于某种原因,这是行不通的。 (更准确的说,虽然我这里只是打印日志,但我实际工作涉及各种计算,使用for循环大约需要5秒才能完成。)

$("#search").click(function() {

$("#search").prop("disabled",true);
$("#search").text("Loading...");

var i;
for(i = 0; i < 50000; i++)
console.log("hi");


$("#search").prop("disabled",false);
$("#search").text("Finished...");
});

https://jsfiddle.net/gs793zhx/

最佳答案

尝试使用 .delay() 并将持续时间设置为 1 , .queue() , .promise() , $.Deferred()

$("#search").click(function() {
$(this).prop("disabled", true)
.text("Loading...")
.css("color", "red")
.delay(1, "p")
.queue("p", function(next) {
next()
})
.dequeue("p")
.promise("p")
.then(function() {
var elem = this;
return $.Deferred(function(d) {
var i = 0, max = 50000;
for (;i < max; i++) {
console.log("hi");
}
if (i === max) {
d.resolveWith(elem, [i])
}
}).promise()
}).then(function(data) {
console.log(this, data);
$(this).prop("disabled", false)
.css("color", "blue")
.text("Finished...");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button type="button" id="search" class="btn btn-primary" style="width:100px; height:30px;">SEARCH</button>

jsfiddle https://jsfiddle.net/gs793zhx/1/

关于计算不起作用后javascript按钮禁用和启用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com