gpt4 book ai didi

javascript - 重复调用同一函数会重置 setTimeout 内部函数

转载 作者:行者123 更新时间:2023-11-28 20:52:49 25 4
gpt4 key购买 nike

全部,

我有一个“信用模块”(类似于游戏中的信用系统),当用户执行操作时,它会创建一个内部 div 并添加或减去成本,以便用户可以看到最后一个操作的成本是多少是。

问题:只要调用该函数一次,一切都可以正常工作,如果用户快速执行多个操作,则 setTimeout 函数(假设动画然后删除成本 div)不会被执行。看来该函数的第二个实例重置了第一个函数的 setTimeout 函数。

(function()
{

$("#press").on("click", function(){creditCost(50)});

function creditCost(x)
{
var eParent = document.getElementById("creditModule");
// following code creates the div with the cost
eParent.innerHTML += '<div class="cCCost"><p class="cCostNo"></p></div>';
var aCostNo = document.getElementsByClassName("cCostNo");
var eLatestCost = aCostNo[aCostNo.length - 1];
// following line assigns variable to above created div '.cCCost'
var eCCost = eLatestCost.parentNode;
// cost being assigned
eLatestCost.innerHTML = x;
$(eCCost).animate ({"left":"-=50px", "opacity":"1"}, 250, "swing");
// following code needs review... not executing if action is performed multiple times quickly
setTimeout(function()
{
$(eCCost).animate ({"left":"+=50px", "opacity":"0"}, 250, "swing", function ()
{
$(eCCost).remove();
})
}, 1000);
}

})();

jsfiddle, excuse the CSS

最佳答案

eParent.innerHTML += '<div class="cCCost"><p class="cCostNo"></p></div>';

是坏线。这会重置元素的 innerHTML,重新创建整个 DOM 并销毁之前调用中引用的元素 - 让它们的超时失败。请参阅"innerHTML += ..." vs "appendChild(txtNode)"了解详情。当 jQuery 可用时,为什么不使用它呢?

function creditCost(x) {
var eParent = $("#creditModule");
// Create a DOM node on the fly - without any innerHTML
var eCCost = $('<div class="cCCost"><p class="cCostNo"></p></div>');

eCCost.find("p").text(x); // don't set the HTML if you only want text

eParent.append(eCCost); // don't throw over all the other children
eCCost.animate ({"left":"-=50px", "opacity":"1"}, 250, "swing")
.delay(1000) // of course the setTimeout would have worked as well
.animate ({"left":"+=50px", "opacity":"0"}, 250, "swing", function() {
eCCost.remove();
});
}

关于javascript - 重复调用同一函数会重置 setTimeout 内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12123596/

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