How to use delegated events?

2019-06-05 15:43发布

I'm using an event to replace "src" attributes in some layers (<div class="total-title" src="anURL">):

$('.playOnAP').on('click',function() {
    $('#mp3-list ul li',this).each( function( index, element ) {
    $('.total-title').eq(index).attr('src', $(this).text() );
});     

and it works the first time, but not after an Ajax request, when the $('.playOnAP') elements are replaced. I'm guessing I should use Delegated Events, but don't make myself clear.

I've tried the next:

$('.playOnAP').on('click','#mp3-list ul li',function() {
$('.playOnAP #mp3-list ul li').on('click',function() {
$('.playOnAP #mp3-list ul li').on('click','#mp3-list ul li',function() {

but doesn't work.

2条回答
男人必须洒脱
2楼-- · 2019-06-05 15:58

You need to put the delegate on a parent of .playOnAp if you are replacing .playOnAp. The event handlers only attach to DOM elements that exist when you add the event handler.

查看更多
Rolldiameter
3楼-- · 2019-06-05 16:13

Try this:

$(document).on('click', '.playOnAP',function() {

When using event delegation, you must bind the event to an element that was originally in the DOM. If something has been dynamically replaced, you cannot bind to that.

As Anup insightfully mentioned, it is not strictly necessary to bind the click event to document -- any parent element will do, as long as it was originally in the DOM.

For example, if .playOnAP is the topmost container element that is being replaced:

<div id="someDiv">
    <div class="playOnAP">
        //some stuff here
    </div>
</div>

You could use:

$('#someDiv').on('click', '.playOnAP', function() { //do your stuff });

As a default, though, you can pretty much always use $(document).on() (even if just as a quick check to make sure everything works before narrowing down to the most appropriate element).

查看更多
登录 后发表回答