var message = 'Spoon!';
$('#foo').bind('click', function() {
alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
alert(message);
});
为什么两条输出信息是相同的:“不在脸上!”; 关闭'foo'的第一条消息是不是指'Spoon!'? 为什么不? 请有人解释一下。我不理解教程的解释。
答案 0 :(得分:7)
那是因为事件处理程序是异步启动的。 您正在设置的消息值在第一个线程中完成。
所以基本上你的程序会读取你的整个代码,将值设置为'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);
});
答案 1 :(得分:1)
点击foo
后,它会提醒message
的最后一个值,即“不在脸上”!因为在加载页面时已经执行了这行代码。
答案 2 :(得分:0)
答案 3 :(得分:0)
// 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);
});