下面的代码有区别吗?

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

其他回答

新元素

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

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

从互联网和一些朋友那里了解到,.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事件只在元素被渲染时起作用,并且只在DOM准备好时附加到加载的元素上。

.on事件动态地附加到DOM元素,当你想要将事件附加到ajax请求或其他东西(在DOM准备好之后)上呈现的DOM元素时,这是很有用的。

$('.UPDATE').click(function(){ }); **V/S**    
$(document).on('click','.UPDATE',function(){ });

$(document).on('click','.UPDATE',function(){ });

它比$('.UPDATE').click(function(){})更有效; 它可以使用更少的内存,并为动态添加的元素工作。 有时动态获取的数据与编辑和删除按钮不生成JQuery事件时,编辑或删除数据行数据的表单,该时间$(document).on('click','.UPDATE',function(){});是有效的工作,就像相同的获取数据使用jquery。更新或删除时按钮不工作: