javascript如何执行一个接一个的方法

时间:2013-05-02 00:39:24

标签: javascript html5

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

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

我如何克服这个问题?

使用Javascript:

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

HTML:

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

1 个答案:

答案 0 :(得分:3)

您正在做什么不起作用

  

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

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

如果希望JavaScript与其他页面上的JavaScript通信,请通过其他方式进行:URI中的#anchor,URI中的查询字符串,表单数据,sessionStorage,localStorage,或者cookies - 这些是按照永久性和适当性的顺序排列的,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;
}