JQuery 事件侦听器匹配案例

JQuery event listeners match cases

我曾经使用 jquery 在网页中处理事件。 最近几天我在初始化事件时遇到了问题。

我添加一个简单的例子来让我的问题更清楚。我们暂时考虑 click 事件。

<div id="ex"></div>的点击事件我一般写成

方法一

$('#ex').click(function(e) {
  //code
});

而且我知道我们可以写,

方法二

$('#ex').on('click', function(e) {
  //code
})

方法三

$(document).on('click', '#ex', function(e) {
  //code
})

Now the problem is I saw only few of the element's events are working only for method 3. At the same time I have method 1 and method 2 for other element in the same file, they are working perfectly. But only few elements and not following the method 1 and 2.

可能是什么原因?这和我的css有关吗?怎么理解方法一和方法二和方法三用在什么地方?

  1. 当dom中已经存在该元素时,可以使用第一种方法
  2. 当你想附加点击、蓝色等多个事件时,可以使用第二种方法。
  3. 当你的元素在dom中不存在,而是动态注入到dom中,那么你可以使用第三种方法。