简体   繁体   中英

Best Practice with jquery functions and ajax

I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work.

Below is what I'm currently doing to make my jquery work on a stand alone page without ajax.

$('.microContentWrap').click(function(){

    //perform some functions

});

In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. Without this step, the above code was not executing on the ajax page.

$("ajax-wrapper").on("click", ".microContentWrap", function() { 

    //exact same functions as above

});

Both of these things work, but is this the most efficient way? Seems repetitive to do this two step process for every single function in my file.

$("ajax-wrapper").on("click", ".microContentWrap", function() { 

    //exact same functions as above

});

Is saying: "when I click within 'ajax-wrapper' check to see if the element I clicked is 'microContentWrap', if it is, then do this function". The benefit of this approach is that 'microContentWrap' doesn't need to exist when you bind the click even listener.

Another approach would be to add the event listener to 'microContentWrap' in your ajax callback function. So for example:

$.ajax({
    url:"getvalue.php",  
    success:function(data) {
         $('body').append('<div class="microContentWrap"></div>');
         $('.microContentWrap').click(function(){}); 
    }
  });

The solution to this was actually very simple, I just didn't understand binding. The problem I was having was that the ajax-wrapper gets destroyed after the microContent comes in. On other non-ajax pages there was no ajax-wrapper which is why I thought there needed to be two functions. By binding to the body, I eliminated the issue.

$("ajax-wrapper").on("click", ".microContentWrap", function() { 

    //exact same functions as above

});

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