下面的代码有区别吗?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
下面的代码有区别吗?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
当前回答
它们看起来是一样的……click()函数的文档:
这个方法是.bind('click', handler)的快捷方式。
on()函数的文档:
从jQuery 1.7开始,.on()方法提供了所需的所有功能 用于附加事件处理程序。获取从旧jQuery转换的帮助 事件方法,请参见.bind(), .delegate()和.live()。删除事件 与.on()绑定,请参见.off()。
其他回答
它们看起来是一样的……click()函数的文档:
这个方法是.bind('click', handler)的快捷方式。
on()函数的文档:
从jQuery 1.7开始,.on()方法提供了所需的所有功能 用于附加事件处理程序。获取从旧jQuery转换的帮助 事件方法,请参见.bind(), .delegate()和.live()。删除事件 与.on()绑定,请参见.off()。
正如其他答案所提到的:
$("#whatever").click(function(){ });
// is just a shortcut for
$("#whatever").on("click", function(){ })
请注意.on()支持一些.click()不支持的其他参数组合,允许它处理事件委托(取代.delegate()和.live())。
(显然还有其他类似的快捷方法,如“keyup”,“focus”等)
我发布一个额外的答案的原因是提到如果你调用无参数的.click()会发生什么:
$("#whatever").click();
// is a shortcut for
$("#whatever").trigger("click");
请注意,如果你直接使用.trigger(),你还可以传递额外的参数或jQuery事件对象,这是你不能用.click()做的。
我还想提一下,如果你查看jQuery源代码(在jQuery -1.7.1.js中),你会看到内部的.click()(或.keyup()等)函数实际上会调用.on()或.trigger()。显然,这意味着您可以确信它们确实有相同的结果,但这也意味着使用.click()有一点点额外的开销—在大多数情况下无需担心或考虑,但理论上在特殊情况下这可能很重要。
编辑:最后,请注意.on()允许你在一行中将多个事件绑定到同一个函数,例如:
$("#whatever").on("click keypress focus", function(){});
在这里,您将获得应用点击事件的不同方式的列表。你可以选择相应的,如果你的点击不工作,只是尝试一个替代这些。
$('.clickHere').click(function(){
// this is flat click. this event will be attatched
//to element if element is available in
//dom at the time when JS loaded.
// do your stuff
});
$('.clickHere').on('click', function(){
// same as first one
// do your stuff
})
$(document).on('click', '.clickHere', function(){
// this is diffrent type
// of click. The click will be registered on document when JS
// loaded and will delegate to the '.clickHere ' element. This is
// called event delegation
// do your stuff
});
$('body').on('click', '.clickHere', function(){
// This is same as 3rd
// point. Here we used body instead of document/
// do your stuff
});
$('.clickHere').off().on('click', function(){ //
// deregister event listener if any and register the event again. This
// prevents the duplicate event resistration on same element.
// do your stuff
})
.click事件只在元素被渲染时起作用,并且只在DOM准备好时附加到加载的元素上。
.on事件动态地附加到DOM元素,当你想要将事件附加到ajax请求或其他东西(在DOM准备好之后)上呈现的DOM元素时,这是很有用的。
他们现在已经弃用了click(),所以最好使用on('click')