简体   繁体   中英

Pass URL parameter to href using JavaScript

I've got some JavaScript to retrieve a URL parameter, check if the parameter called "pc" was found and if it's value is "tmgppc5" or "tmgggr1", then append to all hrefs on the page.

var pc = getQueryVariable("pc"),
url = 'http://www.thisurl.com';

// Check if the parameter called "pc" was found and if it's value is "tmgppc5" or "tmgggr1"
if (pc && pc === "tmgppc5" || "tmgggr1") {
    url += "pc=" + pc; 
}

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

var elements = document.getElementsByTagName('href')[0];
elements.setAttribute('href',url);

I'm using getElementsByTagName to search for all hrefs, however I get the error: uncaught type error cannot read property 'setAttribute' of undefined

Using getElementsById on a single href works, using getElementsByClassName returns the same error. What's the cause of the error? Is there an alternative? Thanks.

You have 2 errors there, 1. you are searching for "href" instead of "a" and secondly you can not setAttribute on node collection, try to loop trough them :

var elements = document.getElementsByTagName('a');
// You can also use document.querySelectorAll("a")
for (var i=0; i< elements.length; i++) {
     elements[i].setAttribute('href',url);
}

标签是一个示例(链接<a href=""></a> ),如果链接是锚点,则可以使用getElementsByTagName('a')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM