Adding event listeners to current and future elements with a particular class

前端 未结 3 655
挽巷
挽巷 2021-01-01 10:17

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

3条回答
  •  臣服心动
    2021-01-01 10:49

    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).

提交回复
热议问题