我想根据查询字符串将自定义ID附加到链接,我找到了Gregory的this very helpful post(请查看它以获取一些上下文)。
我想要实现的是,如果我访问www.mydomain.com,我需要将默认值添加到网页上的链接,例如:www.ramdomdomain.com?myID1=default_value
我想在代码中的if(hrefvalue==null)
行之后必须编辑某些内容,但我无法弄清楚如何操作。请帮我。以下是我正在使用的代码:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function getHrefValue(key,url){
var query=new RegExp("[\\?&]"+(key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"))+"=([^&#]*)").exec(url);
return (query==null)?null:query[1];
}
function matchHrefs(){
var config={
'myid1':["#topnav a[href^='http://www.domain.com']"],
'myid2':["#topnav a[href^='http://www.domain.com']"]
}
for(var current in config){
var myvalue=getHrefValue(current,location.search);
if(myvalue!=null&&myvalue!=""){
$(config[current].join(',')).each(function(){
var href=$(this).attr('href');
var hrefvalue=getHrefValue(current,href);
if(hrefvalue==null){
var href_split=href.split('#');
$(this).attr('href',href_split[0]+(href_split[0].indexOf('?')>-1?'&':'?')+current+'='+myvalue+(typeof(href_split[1])!="undefined"?'#'+href_split[1]:''));
$(this).addClass('selected selected-'+current);
}
if(hrefvalue==""){
$(this).attr('href',href.replace(current+'=',current+'='+myvalue));
$(this).addClass('selected selected-'+current);
}
});
}
}
}
$(function(){matchHrefs();});
</script>
<div id="topnav"><a href="http://www.domain.com/" target="_blank">Random domain</a></div>
答案 0 :(得分:1)
这就是你所追求的:
<div>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
<script type="text/javascript">
$(function() {
var requestid = new String(gup('myid'));
if (requestid == "") {
requestid = "unknown";
}
$("a").each(function() {
var href = $(this).attr("href");
href += "?myId=" + 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>
<div id="topnav">
<a href="http://www.google.com" target="_blank">Random domain</a>
<a href="http://www.yahoo.com" target="_blank">Random domain</a>
</div>
</div>