脚本标签在 DOM 中移动时出现无法解释的行为?
我发现一些奇怪的行为试图重现其他东西,我认为这很有趣。
我的jsbin示例在这里
核心代码:(
<div id="diag">
<script type="text/javascript">
$(document).ready(function(){
if(x==undefined){
var x=1;
}else{
x=x+1;
}
alert(x);
});
</script>
</div>
页面底部)
$(document).ready(function(){
$('#diag').dialog();
});
$.dialog
我知道会在 DOM 中移动这个脚本,所以预计它会被执行两次。然而,结果与我的预期不同。
我原以为它会先说 1,然后再说 2。然而,它又说 1,然后又说 1。这怎么可能?此行为在 Firefox5、Chrome 和 IE8 中是一致的
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 expected 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
x 的范围在该函数内部,它在第二次调用时重新定义
the scope of x is inside that function, it is redefined on the 2nd call
“x”变量的范围是 if 语句的块。这意味着 x 在这里被定义:
然后被销毁并在这里返回到 undefined:
你要做的是确保 x 是在更大的范围内定义的。
The scope of the "x" variable is the block for the if statement. This means that x is defined here:
And then is destroyed and returns to undefined here:
What you want to do is make sure that x is defined in a larger scope.