关于jQuery的奇怪输出

时间:2012-04-10 15:13:59

标签: jquery


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

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

为什么两条输出信息是相同的:“不在脸上!”; 关闭'foo'的第一条消息是不是指'Spoon!'? 为什么不? 请有人解释一下。我不理解教程的解释。

4 个答案:

答案 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)

只有函数的绑定发生。当点击evenet发生时,代码的实际执行发生。当click事件占用时,message变量将是它的最后一个值'Not in face'

答案 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);
});