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

前端 未结 3 654
挽巷
挽巷 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:38

    you'll want to use event delegation. jquery 1.7 has made this more abstract than previous versions, but it looks something like this:

    $("#myWrappingElement").on("click", ".myclass", function(event){
        alert($(this).text());
    });
    

    this basically adds a click event listener to the #myWrappingElement element, and jquery will automagically look to see what the original event target was and fire the proper function. this means you can add or remove .myclass elements and still have events fire on them.

提交回复
热议问题