-2

我的代码中有一些动画,我遇到了一个问题:当用户多次单击按钮时,我的动画会变得越来越快。为了解决这个问题,我在location.reload()下面的函数中包含了刷新页面函数 ( )。

现在我有一个主要问题:当我执行按钮时,应该首先执行重新加载页面功能,然后是 day2 功能,然后是 day1 功能......问题现在只执行了刷新页面功能。

我该如何克服这个问题?

Javascript:

function day()
{
    location.reload().then(day2).then(day1);
}

HTML:

<input type="button" id="buttonThree" value="Day" onclick="day()"/>
4

1 回答 1

3

你在做什么不起作用

现在我有一个主要问题:当我执行按钮时,应该首先执行重新加载页面功能,然后是 day2 功能,然后是 day1 功能......问题现在只执行了刷新页面功能。

嗯,是的。您刷新了页面。这涉及离开页面然后重新进入它。离开页面意味着你的 JavaScript 结束了它正在做的一切,重新进入它意味着你的 JavaScript 重新开始。JavaScript 不会超越页面加载。

如果您希望您的 JavaScript 与其他页面上的 JavaScript 进行通信,请通过其他方式进行:URI 中的#anchor、URI 中的查询字符串、表单数据、sessionStorage、localStorage 或 cookie - 这些按永久性排列和适当性,cookie 完全过度,#anchors 和查询字符串完全适当。

但这在这里是完全没有必要和不恰当的。你一开始就不应该做你正在做的事情。

让我们解决多个按钮按下的实际问题

我的代码中有一些动画,我遇到了一个问题:当用户多次单击按钮时,我的动画会变得越来越快。

简单地说,你不应该做你正在做的事情,这个问题有一个更简单的解决方案:禁用按钮,或设置一个布尔标志,以防止动画多次运行。简单地说,不要让动画运行多次。

选项 1:禁用按钮

禁用该按钮会阻止它发送onclick事件,并向您的用户发出信号,该按钮暂时不会执行任何操作。如果您的按钮在动画运行时或发生其他事情时不应再做任何事情,我建议您这样做。

方法是在单击按钮后立即禁用该按钮。稍后,一旦该按钮触发的任务(例如动画)完成,并且可以再次单击该按钮,您就可以重新启用该按钮。

<input type="button" id="animateButton" value="Animate" onclick="animate()"/>
function animate() {
    // 'this' refers to the button, when the button's click event
    // calls this function
    this.disabled = true;
    startAnimation();
}

function startAnimation() {
    // run the animation
    // ...

    // once the animation is completed, via whatever means you want
    // (such as by jQuery's animate.complete callback),
    // re-enable the button like this:
    document.getElementById("animateButton").disabled = false;

    // or address the button some other appropriate way.
}

选项 2:布尔标志,使按钮处于启用状态但什么也不做

这种方法涉及在动画运行时使用布尔标志来忽略点击,而不是直接禁用按钮。

这让用户仍然可以单击按钮。如果您出于任何原因想要启用按钮,例如如果您希望按钮在单击时执行其他操作 - 只是无需每次都启动动画,这将非常有用。

但是,如果它除了启动动画之外什么都不做,那么您可能应该使用选项 1 来禁用它,表示该按钮现在不会做任何事情。

如果你想让这个按钮做其他事情,我建议你让它调用一个不同的函数——例如doStuff()——并让那个函数调用animate()下面的函数。

<input type="button" id="animateButton" value="Animate" onclick="animate()"/>
var canAnimate = true;

function animate() {
    if (!canAnimate) return; // do nothing if we're not allowed to animate yet
    canAnimate = false;
    startAnimation();
}

function startAnimation() {
    // run the animation
    // ...

    // once the animation is completed, via whatever means you want
    // (such as by jQuery's animate.complete callback),
    // set the flag to say we can animate again, like this:
    canAnimate = true;
}
于 2013-05-02T00:48:16.560 回答