关于jQuery的奇怪输出

问题描述:


var message = 'Spoon!'; 
$('#foo').bind('click', function() { 
alert(message); 
}); 

message = 'Not in the face!'; 
$('#bar').bind('click', function() { 
alert(message); 
}); 

为什么两个输出信息是一样的:“不要在脸上!”; 'foo'封闭中的第一条消息是不是指'勺子!'? 为什么不呢? 请有人解释。我不明白教程的解释。关于jQuery的奇怪输出

+3

**请**阅读[如何接受答案工作?](http://meta.stackexchange.com/a/5235/170679) - 25%不好... – ManseUK 2012-04-10 15:25:48

这是因为事件处理程序是异步启动的。 虽然您设置的消息值是在第一个线程中完成的。

所以基本上你的程序会读你的整个代码,设置值为'Spoon!',然后到最后一个你设置的'Not in the face!'。然后当你点击任一按钮时,它会提醒消息'Not in the face!'的值。

尝试将消息放入函数中,然后您会看到每个消息的不同消息。这会按照您的预期工作,因为您也异步设置了该值。

$('#foo').bind('click', function() { 
    var message = 'Spoon!'; 
    alert(message); 
}); 

$('#bar').bind('click', function() { 
    var message = 'Not in the face!'; 
    alert(message); 
}); 
+0

哦。我知道了......编译器会将变量“message”设置为“不在脸上!”第一。当两个按钮中的一个被触发时,它会得到'Not in the face'值。那是对的吗?感谢所有的答案! – Stallman 2012-04-11 09:15:03

单击foo时,会提示最后一个值为message,这将是“不在脸上!”因为这行代码已经在页面加载时执行。

仅结合功能的情况发生在点击evenet occurs.When单击事件occues的代码。实际执行发生的消息变量将其最后的值是“未在脸”

// below you are estblishing the "variable" message and setting it to the String "Spoon!" 
var message = 'Spoon!'; 
// Here you use the jquery method to tell a button with the ID "foo" 
// to alert the variable "message" 
$('#foo').bind('click', function() { 
    alert(message); // the alert 
}); 

// Here's where you're getting confused 
//Below you are "re-asigning the variable "message" to be the String "Not in the face!" 
message = 'Not in the face!'; 
// below is another click bind to a button, but this time the id name is "bar" 
// so both buttons (foo and bar) are committing the same action, 
// but your variable has been changed to "Not in the face!" and therefor 
// will never display "Spoon!" 
$('#bar').bind('click', function() { 
    alert(message); 
}); 
+0

谢谢你,SpYk3HH。我知道了! – Stallman 2012-04-11 09:14:40