jQuery click handler function does not fire on element added after DOM load

后端 未结 2 1101
孤独总比滥情好
孤独总比滥情好 2021-01-13 06:12

I believe I could do this with .live but that method is deprecated. Here\'s the issue:

I have a click handler function that should fire on any element with the class

相关标签:
2条回答
  • 2021-01-13 06:41

    From http://api.jquery.com/on/

    You are interested in the usage of on:

    .on( events [, selector ] [, data ], handler(eventObject) )
    

    The example JQuery gives is

    $( "#dataTable tbody" ).on( "click", "tr", function() {
        alert( $( this ).text() );
    });
    

    And you should do something similar, where you first select an element that will be static on the page and then the selector of where the click event should be used.

    Best practice is to be as specific as possible, so try to choose a reasonable first target so that JS does not have to check every click event to see if it should run.

    0 讨论(0)
  • 2021-01-13 06:49

    You need to use Event delegation

    jQuery(document).on('click','.myClickEl', function() { 
        var formText='This is some text to paste';
        jQuery(this).parent().next('textarea').val('');
        jQuery(this).parent().next('textarea').val(formText);
    });
    
    0 讨论(0)
提交回复
热议问题