简体   繁体   中英

$ var declaration in Javascript

How should I declare an object variable in Javascript? By mistake, I thought I was in PHP and it worked.

$(res.data).each(function(index, value){
                    $src = value.images.fixed_height;
                    $('<a href="'+value.url+'" target="_blank"><img src="' + $src.url + '" width="' + $src.width +'" height="' + $src.height + '"></a>').load(function(){
                        $(this).appendTo("#results").fadeIn();
                    })
                });

Then, when I tried to think in terms of Javascript it didn't work,

$(res.data).each(function(index, value){
                    var src = value.images.fixed_height;
                    $('<a href="'+value.url+'" target="_blank"><img src="' + src.url + '" width="' + src.width +'" height="' + src.height + '"></a>').load(function(){
                        $(this).appendTo("#results").fadeIn();
                    })
                });

The only difference between the two is that $src in the first snippet is global (or at least outside the local scope of the anonymous function) and src in the second example is local to that function.

Since the first thing you do is setting the variable, that shouldn't matter for this piece of code, so the second snippet should work exactly as the first one.

The only explanation for different behaviour I can think of, is when another piece of code actually uses this global src , and therefor is affected by your second snippet. But this doesn't sound very likely to me, so my guess would be that your test was wrong and either both snippets work, or neither does.

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