简体   繁体   中英

jQuery append string to url after ajax load

I am adding query string to urls using this jQuery

$( 'a' ).attr( 'href', function(index, value) {
return value + '?appp=3';
});    

This works fine, but after the ajax load, the new href's created are not recognized by the above jQuery. Is there a way to reload the code so to affect the new posts URL's which are loaded via ajax. Super thanks.

Perfect, thanks @developer, that worked nicely. Here how I did it as you mentioned:

 function apendquery(){
 $( 'a' ).attr( 'href', function(index, value) {
 return value + '?appp=3';
 });
 };


 $(document).ready(function(){
 apendquery();
 });

 $(document).ajaxComplete(function () {
 apendquery();
 });

Of course it wont work on new elements. You can create function which you shuold call each time when new 'a' elements appears in DOM. Also you will need to create some kind of flag which helps you identify and update the href only for the new elements.

var updateHref = function(){
   $( 'a[data-updated!=1]' ).attr( 'data-updated',1).attr( 'href',   
    function(index, value) {
      return value + '?appp=3';
    }); 
};
...
$.ajax(...)
 .done(function() { 
  ...
  // add new 'a' tags
  ....
  // then call our function to update href
  updateHref();
});

Actually here is my final code which is better version in case the URL already appended a query should anyone might find useful:

function apendquery() {
    $('a').attr('href', function(index, value) {
        return value + (value.indexOf('?') !== -1 ? "&" : "?") + 'appp=3';
    });
};

$(document).ajaxComplete(function() {
    apendquery();
});

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