我正在尝试做并且主要完成的是更改 URL 中的 tag 参数以用于包裹在跨度中的锚标记。那工作正常。发生的事情是它拉出第一个锚标记href,并用相同的href替换所有锚标记。我认为当它通过循环时,它每次都会用新的href替换var。建议?
<div class="changeparam">
<span><a href="http://demo.org/post.php?i=17uh23&p=456&s=789&tag=asdf">Link</a></span>
<span><a href="http://demo.org/post.php?i=18uh23&p=456&s=789&tag=asdf">Link</a></span>
<span><a href="http://demo.org/post.php?i=19uh23&p=456&s=789&tag=asdf">Link</a></span>
<span><a href="http://demo.org/post.php?i=20uh23&p=456&s=789&tag=asdf">Link</a> </span>
<a href="www.test.com">test</a>
</div>
这是我的代码,它确实替换了锚标记中的标记参数。该功能运行良好。我的问题出在函数 displayTextNumber() 中。它存储它找到的第一个锚标记并使用它来替换整个站点中的所有其他锚标记href。我想遍历每个标签。
function replaceQueryString( queryString, keys, newValues ) {
var parts = queryString.split('&');
// We're going to make an array of querystring key=value strings
var new_parts = [];
for( i in parts ) {
var keyValue = parts[i].split('=');
// Use jQuery to see if this key is in our desired set
var replacePos = $.inArray(keyValue[0],keys);
// If it is, it will give a non-negative integer, if not it'll give -1
if( replacePos >= 0 )
// We want to replace this key so make a new string for the key/value pair
new_parts.push( keyValue[0] + '=' + newValues[replacePos] );
else {
// This isn't the key we want to replace, so leave it alone
new_parts.push( parts[i] );
}
}
// glue all the parts together and return them
return new_parts.join('&');
}
function displayTextNumber(){
if(isNotBrandedTerm()){
var NumberSpans = document.getElementsByTagName('span');
for (var i=0; i < NumberSpans.length; i++) {
// Get the full address from the original link
var old_fulladdr = $('span a').attr('href');
var old_addr_parts = old_fulladdr.split('?');
// The keys you want to replace
var tobereplaced = ['tag'];
// The respective values you want to assign
var replacements = [getPhoneNumber()];
var new_query_string = replaceQueryString( old_addr_parts[1], tobereplaced, replacements );
//var new_querystring = 'i=abc&p=def&g=ghi';
$('span a').attr('href',old_addr_parts[0] + '?' + new_query_string);
}//CLOSE IF
} //CLOSE FOR
}//close isNotBrandedTerm