[英]Replacing custom IDs of links based on query-string using javascript
如果當前頁面URL的查詢字符串中具有參數“ myid1”,則對於我的網頁中具有“重寫”類的每個鏈接,我希望將鏈接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
和""
因此您只能使用一個測試。 href
屬性。 僅使用this.href
更快,更直接。 如果您希望更少的代碼行(盡管不是那么快),您可以通過以下方式進行操作:
$(function() {
var requestid = gup('myid1');
if (requestid) {
$("a.rewrite").each(function() {
this.href = this.href.replace(/\?.*$/, "") + "?myid1=" + requestid;
})
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.