What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript) -
i making can loads new setting pages via ajax, not sure what's efficient way bind listeners elements new content page?
here's thought. can make function compares file path, , each condition, apply correct listeners new elements based on page ajax loaded. feel makes function big if have large amount of pages.
thanks!
two ways:
1) bind on non-dynamic parent container using .on()
$('.some-parent-class').on('click', '.element', function() { // stuff! });
2) bind new elements after ajax call completed
$.ajax(url, { // ajax options }).done( function(data) { var newel = $('<div class="element"></div>'); // setup newel data here... newel.on('click', function() { // stuff }); newel.appendto($('.some-parent-class')); });
the former results in quicker ajax response times, may slow click responsiveness down.
Comments
Post a Comment