.click(...)和.live('click',...)有什么区别? [英] What is the difference between .click(...) and .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:
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');
}
此代码按预期工作,即<$ c只有在点击启用
按钮时才会调用$ c> log()。
This code works as expected, i.e. log()
is called only when enabled
button is clicked.
但是,如果我用(2)
替换(1)
, log()如果没有
启用
按钮,也会调用code>。
为什么会这样?
(1)
和(2)
?
But, if I replace (1)
with (2)
, log()
is called also when not enabled
button is clicked.
Why is that ?
What is the difference between (1)
and (2)
?
推荐答案
区别在于 .click( )
将点击
处理程序绑定到该元素。这是最重要的,到元素,所以无论元素 $('#button.enabled')
选择器在绑定时匹配 ,得到绑定......无论选择器以后哪个选择器都不再匹配。
The difference is that .click()
binds a click
handler to the element. That's the most important thing, to the element, so whatever elements the $('#button.enabled')
selector matches at the time it's bound, get bound...regardless of it the selector no longer matches later.
.live()
检查选择器时的时间事件以查看它是否应该运行处理程序...因此更改类 很重要,因为它不再匹配。 .live()
处理程序存在于文档
并依赖于事件冒泡,所以它必须检查选择器,看它是否来自一个应该执行处理程序的元素。
.live()
checks the selector at the time of the event to see if it should run the handler...so changing the class does matter, since it no longer matches. The .live()
handler lives on document
and relies on event bubbling, so it must check the selector to see if it came from an element that it should execute the handler for.
这篇关于.click(...)和.live('click',...)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!