简体   繁体   English

函数不读取全局变量

[英]Function doesn't read global variable

I'm having a litte problem with Javascript and global variables. 我在Javascript和全局变量方面遇到了小问题。 According to an article I read a few minutes ago when searching for a solution, variables defined outside a function are global and can be used all over the document. 根据我几分钟前阅读的一篇文章,当寻找解决方案时,在函数外部定义的变量是全局变量,可以在整个文档中使用。 Well, this doesn't seem to work for me. 好吧,这似乎对我不起作用。 Basically, even why I try to simplify the process to this: 基本上,即使我为什么尝试简化此过程:

var list_amount = 1;
function createElements() {
    window.alert('0');
    var cintfa_list_top = $("<div>").attr({"id":"intfa_list_top"});
    $('#intfa_list').empty()
    $('#intfa_list').append(cintfa_list_top);
    var j=0;
    window.alert('1');
    for (j=0;j<list_amount;j++) {
        window.alert('2');
            ......
            ....
            ..

I get the window.alert for 0 and 1, but not for 2. When I set a window.alert(list_amount) inside the function, it returns undefined. 我得到的window.alert为0和1,但没有为2。当我在函数内设置window.alert(list_amount)时,它返回未定义。 Shouldn't the global variable work inside the function as well? 全局变量是否也应该在函数内部工作? And if I misunderstood something, is there a way to make variables global for functions as well without having to add them to the function parameters? 而且,如果我误解了什么,是否有一种方法也可以使变量成为函数的全局变量,而不必将其添加到函数参数中?

I tried out your code http://jsfiddle.net/lastrose/ALd2b/ and it seems to work fine. 我尝试了您的代码http://jsfiddle.net/lastrose/ALd2b/ ,它似乎可以正常工作。 Only thing I can think is where it is all defined. 我唯一能想到的就是所有定义的地方。

There is an error in your code that hangs the script. 您的代码中有一个错误将脚本挂起。 As it is, closing for and function works very well (also commenting out $, as it's not defined here). 实际上,for和函数的关闭效果很好(也注释掉$,因为这里没有定义)。

Check in Firebug or Chrome/Opera javascript console for errors. 在Firebug或Chrome / Opera JavaScript控制台中签入错误。

LE: After seeing jsfiddle.net/ALd2b/2 you should call the function after variable assignment. LE:看到jsfiddle.net/ALd2b/2之后,您应该在变量分配后调用该函数。

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

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