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

前端 未结 5 810
谎友^
谎友^ 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:24

    Adding on to Populus' answer, which is great as it is, a logically equivalent solution to his second option would be to use Promises:

         var iGotYou = new Promise(function (res, rej) {
            $.ajax({
                 //ajax paramaters
            })
                .done(function( data ) {
                    //handle the data as necessary...
                    //then resolve the Promise
                    res();
                });
        });
    
        //the Promise has been resolved
        iGotYou.then(function (response) {
            //add the event listener now that the promise has been fulfilled
           document.getElementById('someId').addEventListener('click', function (e) {
            //whatever you want to do on click event
           });
        })
    

提交回复
热议问题