简体   繁体   English

引用Javascript中的外部函数(使用jQuery)

[英]Refer to outer function in Javascript (using jQuery)

I have these lines of javascript code which run when the page is loaded: 我有以下这些JavaScript代码行,它们在页面加载时运行:

(function my_function() {
    //my stuff
})();

$("select#myselect").change( function() {
    if ($('select#myselect').val() == '1') {
        timer = setTimeout(my_function, 1000*5); //this line throws the error
    } else {
        if(typeof timer !== 'undefined'){
            clearTimeout(timer);
        }
    }
});

When the line highlighted is executed it throws: "Uncaught ReferenceError: my_function is not defined" 当执行突出显示的行时,它将引发:“ Uncaught ReferenceError:未定义my_function”

How can I fix it? 我该如何解决?

Try to change this: 尝试更改此:

(function my_function() {
    //my stuff
})();

To this: 对此:

function my_function() {
    //my stuff
}
my_function();

Edit: Your function my_function isn't callable in the global scope because this pattern creates a local scope. 编辑:您的函数my_function在全局范围内不可调用,因为此模式创建了本地范围。 Read this excellent wiki article for more informations. 阅读这篇出色的Wiki文章,了解更多信息。

It looks like you are trying to run my_function first, and then run it again with the timer. 看来您正在尝试先运行my_function,然后使用计时器再次运行它。

function my_function() {
    //my stuff
}
my_function();

$("select#myselect").change( function() {
    if ($('select#myselect').val() == '1') {
        timer = setTimeout(my_function, 1000*5); //this line throws the error
    } else {
        if(typeof timer !== 'undefined'){
            clearTimeout(timer);
        }
    }
});

You have what's called a closure going on, whereby you cannot access it (by design). 您正在进行所谓的闭包,因此无法(通过设计)访问它。 Try this instead (also with some additional improvements... 改用此方法(还有一些其他改进...

function my_function() {
    //my stuff
}

// Call your function...
my_function();

var $mySelect = $("select#myselect");

$mySelect.on("change", function() {
    if ($mySelect.val() == '1') {
        timer = setTimeout(my_function, 1000*5); //this line throws the error
    } else {
        if(typeof timer !== 'undefined'){
            clearTimeout(timer);
        }
    }
});

I also cached your look up of select#myselect into a variable...because it will improve performance (admittedly marginally). 我还将您对select#myselect查询缓存到了一个变量中...因为它可以提高性能(略微提高)。 In addition, I used the more preferred and newer on() method for your change event. 另外,对于您的更改事件,我使用了更优选和更新的on()方法。

Hope this helps! 希望这可以帮助!

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

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