需要jQuery代码将参数附加到div中包含的所有URL

Ali*_*Ali 4 javascript jquery

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

Poi*_*nty 12

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

找到所有<a>标签并更新其描述的"href"值.如果需要传递不同的"xyz"值,可以将其转换为jQuery插件:

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

然后你可以做,$('a').addAction("xyz");或者,在你的情况下,

$('#yourDiv a').addAction("xyz");
Run Code Online (Sandbox Code Playgroud)