Unexplained behavior with script tags being moved in the DOM?
I've found some strange behavior trying to reproduce something else and I thought it was interesting.
My jsbin example is here
The core code:
<div id="diag">
<script type="text/javascript">
$(document).ready(function(){
if(x==undefined){
var x=1;
}else{
x=x+1;
}
alert(x);
});
</script>
</div>
(at the bottom of the page)
$(document).ready(function(){
$('#diag').dialog();
});
$.dialog
I know will move this script in the DOM, so it is expe开发者_JAVA百科cted that it will be executed twice. However, the results are different than I would expect.
I expected for it to say 1 and then 2. However, it says 1 and then 1 again. How is that even possible? This behavior is consistent across Firefox5, Chrome, and IE8
the scope of x is inside that function, it is redefined on the 2nd call
var x;
$(document).ready(function(){
if(x==undefined)
x=1;
else
x=x+1;
alert(x);
});
The scope of the "x" variable is the block for the if statement. This means that x is defined here:
var x=1;
And then is destroyed and returns to undefined here:
}else{
What you want to do is make sure that x is defined in a larger scope.
<script type="text/javascript">
var x = 1;
$(document).ready(function(){
if(x == undefined){
x = 1;
} else {
x = x + 1;
}
alert(x);
});
</script>
精彩评论