如果当前页面 URL 在查询字符串中有一个参数“myid1”,对于我网页中每个类为“rewrite”的链接,我希望链接 href 的查询字符串被当前页面 URL 的查询字符串替换。
我正在使用以下代码:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript">
$(function() {
var requestid = new String(gup('myid1'));
if (requestid!=null&&requestid!="") {
$("a.rewrite").each(function() {
var href = $(this).attr("href");
href += "?myid1=" + requestid;
$(this).attr("href", href);
})
}
})
//gup taken from here:http://www.netlobo.com/url_query_string_javascript.html
function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
</script>
<a href="http://www.otherdomain.com?someid=1234" class="rewrite">Hyperlink</a>
问题是 URS 的查询字符串被添加到链接中而没有删除现有的。如何解决?
此外,我如何允许一个名为“myid2”的参数。预先感谢您的帮助。
最佳答案
您可以使用以下方法删除先前的查询字符串:
$(function() {
var requestid = gup('myid1');
if (requestid) {
$("a.rewrite").each(function() {
var base = this.href;
var pos = base.indexOf("?");
if (pos != -1) {
base = base.substr(0, pos);
}
this.href = base + "?myid1=" + requestid;
})
}
})
本次改版需要注意的几点:
if (requestid)
测试null
、undefined
和""
,因此您可以只使用其中一个测试。- 无需使用 jQuery 对象来访问
href
属性。仅使用this.href
会更快更直接。
如果您喜欢更少的代码行(虽然不是那么快),您可以这样做:
$(function() {
var requestid = gup('myid1');
if (requestid) {
$("a.rewrite").each(function() {
this.href = this.href.replace(/\?.*$/, "") + "?myid1=" + requestid;
})
}
})
关于javascript - 使用javascript根据查询字符串替换链接的自定义ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8059581/