简体   繁体   中英

Function doesn't read global variable

I'm having a litte problem with Javascript and global variables. 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. 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. 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).

Check in Firebug or Chrome/Opera javascript console for errors.

LE: After seeing jsfiddle.net/ALd2b/2 you should call the function after variable assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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