将事件侦听器添加到

将事件侦听器添加到

本文介绍了将事件侦听器添加到具有特定类的当前和未来元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JQuery,是否可以向当前或将来的任何元素添加事件侦听器,并拥有特定的类?

我正在研究一个大量使用contentEditable的项目,所以DOM正在改变,元素可以通过用户输入添加和删除类。



我希望能够说X类的元素应该在点击时执行Y,但是如果我理解正确,$(。X)。click(Y)只会将事件侦听器添加到元素目前有类X.



此外,如果一个元素不再是类X的一部分,那么它仍然会有click事件监听器。



我该怎么做?

解决方案

是的。你在说什么叫做事件授权。例如:
$ b $ pre $ '('#container')。on('click','.innerElement',function() {
///做东西
});

在您的情况下, #container 应该是一个已知在页面加载中存在的元素,其中将包含您关心的子元素(现在或将来)。这种方法利用了DOM中的事件冒泡。



另一个海报提到,live方法也可以工作 - 但它在jQuery 1.7中已被弃用,并且一般不如使用更多选择性委托(例如上面的示例)那样高效。

With JQuery, is it possible to add an event listener to any element that currently, or will in the future, have a particular class?

I'm working on a project that makes heavy use of contentEditable, so the DOM is changing, and elements can have classes added and removed as a result of user input.

I would like to be able to say "elements of class X should do Y when clicked", but if I understand correctly, $(".X").click(Y) will only add the event listener to elements that currently have class X.

Furthermore, if an element is no-longer part of class X, then it will still have the click event listener.

How can I do this?

解决方案

Yep. What you're talking about is called event delegation. Here's an example:

$('#container').on('click', '.innerElement', function(){
   /// Do stuff
});

In your case, #container would be an element that is known to exist on page load which will contain the child elements you care about (either now or in the future). This approach takes advantage of event bubbling in the DOM.

As another poster mentioned, the live method will also work -- but it has been deprecated in jQuery 1.7, and is generally not as performant as using more selective delegation (such as the example above).

这篇关于将事件侦听器添加到具有特定类的当前和未来元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:19