下面的代码有区别吗?

$('#whatever').on('click', function() {
     /* your code here */
});

and

$('#whatever').click(function() {
     /* your code here */
});

当前回答

在这里,您将获得应用点击事件的不同方式的列表。你可以选择相应的,如果你的点击不工作,只是尝试一个替代这些。

$('.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
})

其他回答

.on()是jQuery 1.7版本中所有事件绑定的推荐方式。它将.bind()和.live()的所有功能滚动到一个函数中,当您传递不同的参数时,该函数会改变行为。

正如您所写的示例,两者之间没有区别。两者都将一个处理程序绑定到#whatever的单击事件。On()提供了额外的灵活性,允许您将#whatever的子对象触发的事件委托给单个处理程序函数(如果您愿意的话)。

// Bind to all links inside #whatever, even new ones created later.
$('#whatever').on('click', 'a', function() { ... });

从互联网和一些朋友那里了解到,.on()用于动态添加元素。但是当我在一个简单的登录页面中使用它时,点击事件应该发送AJAX到node.js,并返回追加新元素,它开始调用多AJAX调用。当我把它改成click()时,一切都很顺利。其实我以前没有遇到过这个问题。

在这里,您将获得应用点击事件的不同方式的列表。你可以选择相应的,如果你的点击不工作,只是尝试一个替代这些。

$('.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(),所以最好使用on('click')

新元素

如果你想点击附加到新元素,作为上述综合答案的补充,以突出关键点:

第一个选择器所选择的元素(例如$("body"))必须在声明时存在,否则就没有可以附加的元素。 必须使用.on()函数中的三个参数,包括目标元素的有效选择器作为第二个参数。