问题描述
我需要一个将参数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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!