关于jQuery的奇怪输出

Als*_*ton 1 jquery


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

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

为什么两个输出消息是相同的:"不在脸上!"; 关闭'foo'的第一条消息是不是指'Spoon!'?为什么不?请有人解释一下.我不明白教程的解释.

Mic*_*gue 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);
});
Run Code Online (Sandbox Code Playgroud)