简体   繁体   中英

dynamically added content via ajax call can not be targeted with jquery

I am passing dynamically generated html via ajax call, see simple example below

var loadContent = function(){

    $.ajax({
         url: '/url',
         method: 'GET'
    }).success(function (html) { 

         $('.content-wrapper').replaceWith(html);

    }) 

    //this is how simple returned html looks like
    //<div class="content-wrapper"><ul"><li>test</li></ul></div>

};

now if I try to target li to add class nothing happens

var testAjaxGeneratedHtml = function() {
    loadContent();
    $('.content-wrapper ul li').addClass('test');
}

Ajax is asynchronous request it will not wait for the response so add class inside success function after ajax has performed its task completely

var loadContent = function(){

    $.ajax({
         url: '/url',
         method: 'GET'
    }).success(function (html) { 

         $('.content-wrapper').replaceWith(html);
         $('.content-wrapper ul li').addClass('test');


    }) 

    //this is how simple returned html looks like
    //<div class="content-wrapper"><ul"><li>test</li></ul></div>

};

Nitin's answer is correct but I felt I could add a little more explanation...

Most Javascript functions are synchronous - each step has to finish before the next one can begin. Ajax is different, as it consists of a request and a response. It sends the request and establishes a listener to await the response and process it when it comes. Once this listener has been created, your code can continue to run while the response is still pending.

So in your case, you're sending a request and then manipulating the DOM before the response has come back. Presumably a fraction of a second later, the response arrives, your "success" function processes it, and this overwrites what you had momentarily achieved with $('.content-wrapper ul li').addClass('test');

Probably the best solution is to do as Nitin suggested and put that line inside your success handler, but if you must do it inside the testAjaxGeneratedHtml for some reason you can define it as a function:

note: untested code

var loadContent = function(onSuccess){

    $.ajax({
         url: '/url',
         method: 'GET'
    }).success(function (html) { 

         $('.content-wrapper').replaceWith(html);
         onSuccess();

    }) 

    //this is how simple returned html looks like
    //<div class="content-wrapper"><ul"><li>test</li></ul></div>

};

var testAjaxGeneratedHtml = function() {
    loadContent(function() { $('.content-wrapper ul li').addClass('test'); });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM