简体   繁体   English

另一个函数内部的函数不起作用

[英]function inside another function doesn't work

So I have this code: http://jsfiddle.net/7rGSb/1/ 所以我有这段代码: http : //jsfiddle.net/7rGSb/1/

var volumeDiv = document.getElementById("volumeNumber");
var volumeOld = 8;
var volumeNew = 37;
var timeNew = (1000 / (volumeNew - volumeOld));
changeVolume();

function changeVolume() {
    volumeDiv.innerHTML = volumeOld;
    volumeOld++;
    if (volumeOld <= volumeNew) setTimeout(changeVolume, timeNew);
};​

it's a string going from 8 to 37 in 1 second. 它是一个字符串,在1秒内从8变为37。 It is working fine. 一切正常。

However when I try to put it into a click event handler ( http://jsfiddle.net/wH2qF/1/ ), it stops working: 但是,当我尝试将其放入点击事件处理程序( http://jsfiddle.net/wH2qF/1/ )时,它将停止工作:

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

        setTimeout(triggerVolumeChange, 4000);

        function triggerVolumeChange() {

            var volumeDiv = document.getElementById("volumeNumber");
            var volumeOld = 8;
            var volumeNew = 37;
            var timeNew = (1000 / (volumeNew - volumeOld));
            changeVolume();

            function changeVolume() {
                volumeDiv.innerHTML = volumeOld;
                volumeOld++;
                if (volumeOld <= volumeNew) setTimeout(changeVolume, timeNew);
            };

        };

    });
});​

Any idea why? 知道为什么吗?

Is it because I'm calling changeVolume(); 是因为我正在调用changeVolume(); inside another function? 内另一个功能? If so, how can I make that function work without having to call it? 如果是这样,如何使该函数工作而不必调用它?

You have MooTools selected, but it looks like you're using jQuery's .ready() and DOM selection syntax. 您已经选择了MooTools ,但看起来您正在使用jQuery的.ready()和DOM选择语法。

Choose one of the jQuery options from the menu on the left. 从左侧菜单中选择jQuery选项之一。 Or get rid of the outer $(function() {...}); 或者摆脱外面的$(function() {...}); and update the selection/handler code. 并更新选择/处理程序代码。

Why do you have Nested functions when not required in this scenario.. 为什么在这种情况下不需要嵌套功能

Move the function declarations to the outside 将函数声明移到外部

$(function() {
    $("#Volume").click(function() {
        setTimeout(triggerVolumeChange, 4000);
    });
});

var volumeDiv = document.getElementById("volumeNumber");
var volumeOld = 8;
var volumeNew = 37;
var timeNew ;

function triggerVolumeChange() {
    timeNew = (1000 / (volumeNew - volumeOld));
    changeVolume();
};

function changeVolume() {
    volumeDiv.innerHTML = volumeOld;
    volumeOld++;
    if (volumeOld <= volumeNew) 
        setTimeout(changeVolume, timeNew);
};​

Also make sure the Framework is set to jQuery .. 还要确保将Framework设置为jQuery ..

Check Fiddle 检查小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM