Unable to get jQuery on() to register dynamically added content

前端 未结 2 2039
孤城傲影
孤城傲影 2021-01-13 09:06

I\'m quite new to the on() method in jQuery but the time has come for me to need to use it.

I\'ve two functions for clicking on specific buttons. Each function works

2条回答
  •  甜味超标
    2021-01-13 09:27

    There are two ways to use .on(), and you're using the wrong type.

    You can bind event handlers directly to elements using $('selector for elements you want the event handler bound to').on('event', function() {...});

    Or, you can delegate events, by calling .on() on a wrapper element that will contain all of the dynamically added elements, such as a div or, in the worst case, the element. Code would look something like this:

    
    
    $('#wrapper').on('click', '.link', function(e) {
        // code to handle the click event on the link here
    });
    

    The event handler is actually handled by the

    element once the event has bubbled up to it, but the function is only called if the original target matches the selector provided. With this method, you can dynamically add additional elements with the class link to the div, and the function will also run when they're clicked on.

提交回复
热议问题