需要jQuery代码将参数附加到div中包含的所有url中 [英] Need jQuery code to append parameters to all urls contained in a div

查看:100
本文介绍了需要jQuery代码将参数附加到div中包含的所有url中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个将参数action=xyz附加到页面内所有url的jQuery代码片段-请注意,还应检查url是否已经附加了其他参数:例如,对于诸如index.php?i=1的url它应该附加&action=xyz,对于没有参数的网址,例如index.php,它应该附加?action=xyz.

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=xyz.

推荐答案

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

这将找到所有的<a>标记并按照您的描述更新其"href"值.如果您需要传递不同的"xyz"值,则可以将其变成jQuery插件:

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);
    }
  };
}

然后您可以执行$('a').addAction("xyz");,或者根据您的情况

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

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

这篇关于需要jQuery代码将参数附加到div中包含的所有url中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆