2012-04-10 60 views
1

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

回答

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); 
}); 
+0

哦。我知道了......編譯器會將變量「message」設置爲「不在臉上!」第一。當兩個按鈕中的一個被觸發時,它會得到'Not in the face'值。那是對的嗎?感謝所有的答案! – Stallman 2012-04-11 09:15:03

1

單擊foo時,會提示最後一個值爲message,這將是「不在臉上!」因爲這行代碼已經在頁面加載時執行。

0

僅結合功能的情況發生在點擊evenet occurs.When單擊事件occues的代碼。實際執行發生的消息變量將其最後的值是「未在臉」

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); 
}); 
+0

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