考慮following code:.click(...)和.live('click',...)之間有什麼區別?
HTML:
<div id='button' class='enabled'>Press here</div>
<div id='log'></div>
CSS:
#button {
width: 65px;
height: 25px;
background-color: #555;
color: red;
padding: 10px 20px;
}
#button.enabled {
color: #333;
}
#button.enabled:hover {
color: #FFF;
cursor: pointer;
}
的JavaScript:
$(function() {
$('#button.enabled').live('click', function() { // (1)
//$('#button.enabled').click(function() { // (2)
log('#button.enabled clicked');
});
});
function log(str) {
$('#log').append(str + '<br />');
$('#button').toggleClass('enabled');
}
此代碼正常工作,即log()
被稱爲只有當單擊0按鈕。
但是,如果我將(1)
替換爲(2)
,則log()
也會在不單擊enabled
按鈕時被調用。
這是爲什麼? (1)
和(2)
有什麼區別?
非常感謝Nick!你是最棒的 !! – 2010-09-06 12:13:22
@Misha - welcome :)希望能夠清楚地說明這一點,對於許多* jQuery用戶來說,這絕對是一個混亂點。 – 2010-09-06 12:16:18