下面的代码有区别吗?
$('#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事件只在元素被渲染时起作用,并且只在DOM准备好时附加到加载的元素上。
.on事件动态地附加到DOM元素,当你想要将事件附加到ajax请求或其他东西(在DOM准备好之后)上呈现的DOM元素时,这是很有用的。
从互联网和一些朋友那里了解到,.on()用于动态添加元素。但是当我在一个简单的登录页面中使用它时,点击事件应该发送AJAX到node.js,并返回追加新元素,它开始调用多AJAX调用。当我把它改成click()时,一切都很顺利。其实我以前没有遇到过这个问题。
他们现在已经弃用了click(),所以最好使用on('click')
下面的代码有区别吗?
不,在你的问题中的两个代码示例之间没有功能上的区别。click(fn)是.on(“click”,fn)的“快捷方法”。来自.on()的文档:
对于一些事件(如.click()),可以使用一些简写方法来附加或触发事件处理程序。有关简写方法的完整列表,请参见事件类别。
请注意,.on()与.click()的不同之处在于,它能够通过传递选择器参数来创建委托事件处理程序,而.click()则不能。当不带选择器参数调用.on()时,它的行为与.click()完全相同。如果需要事件委托,请使用.on()。
在这里,您将获得应用点击事件的不同方式的列表。你可以选择相应的,如果你的点击不工作,只是尝试一个替代这些。
$('.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
})