开发者

Need jQuery code to append parameters to all urls contained in a div

开发者 https://www.devze.com 2023-01-04 05:27 出处:网络
I need a jQuery code snippet which appends the parameter action=xyz to all urls within a page - note it should also check that if the urls already have other parameters appended or not: e.g., for a ur

I need a jQuery code snippet which appends the parameter action=xyz to all urls within a page - note it should also check that if the urls already have other parameters appended or not: e.g., for a url such as index.php?i=1 it should append &action=xyz and for urls without parameters like index.php it should append ?action=xy开发者_StackOverflow社区z.


$('a').each(function() {
  this.href += (/\?/.test(this.href) ? '&' : '?') + 'action=xyz';
});

That finds all the <a> tags and updates their "href" value as you described. You could turn it into a jQuery plugin if you need to pass different "xyz" values:

jQuery.fn.addAction = function(action) {
  return this.each(function() {
    if ($(this).is('a')) {
      this.href += (/\?/.test(this.href) ? '&' : '?') + 'action=' + escapeURLComponent(action);
    }
  };
}

Then you could just do $('a').addAction("xyz"); or, in your case,

$('#yourDiv a').addAction("xyz");
0

精彩评论

暂无评论...
验证码 换一张
取 消