What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript)

前端 未结 5 809
谎友^
谎友^ 2021-01-05 09:13

I am making something that can loads new setting pages via AJAX, I am not sure what\'s the most efficient way to bind listeners to those elements from the new content page?<

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 09:26

    Two ways:

    1) Bind on a non-dynamic parent container using .on()

    $('.some-parent-class').on('click', '.element', function() {
      // DO STUFF!
    });
    

    2) Bind the new elements after ajax call is completed

    $.ajax(url, {
      // ajax options
    }).done( function(data) {
      var newEl = $('
    '); // Setup your newEl with data here... newEl.on('click', function() { // do stuff }); newEl.appendTo($('.some-parent-class')); });

    The former usually results in quicker ajax response times, but may also slow click responsiveness down.

提交回复
热议问题