简体   繁体   中英

javascript - changing href of a link

I've got a site which includes jQuery-Tabs, so I have a hashtag in my url to get a desired tab displayed:

www.abc.de/site#tab4

On this site I have a link which looks like this:

<a href="/site.html?option=1" name="optionslink" id="optionslink" onclick="javascript:test()">LINKTEXT</a>

With this link the user can choose an option for a product. The site gets reloaded on click. I want to achieve that on click the string after the hashtag in the url is read out and then this string will be added to the url or the link...

My function looks like this:

function test() {
var info=window.location.hash;
alert(info);
document.getElementById("optionslink").href+info;
return true;
}

So far the function is on click I get an alert-popup which shows the correct hashtag and it's string. But the site gets reloaded without having the hashtag+string added. It looks like this:

www.abc.de/site.html?option=1

It should look like:

www.abc.de/site.html?option=1#tab4

How can I get this working?

You are not changing the href attribute. Try

document.getElementById("optionslink").href += info;

Your code document.getElementById("optionslink").href+info; just has no effect, as there is just the concatination, but no assignment to the href attribute.

Simply change the location:

function test() {
    var info=window.location.hash;
    window.location = document.getElementById("optionslink").href + info;
    return false;
}

<a href="/site.html?option=1" name="optionslink" id="optionslink" onclick="return test();">LINKTEXT</a>

Another thing, you pass the current anchor to the function, and save the DOM query overhead:

function test(anchor) {
    var info=window.location.hash;
    window.location = anchor.href + info;
    return false;
}

<a href="/site.html?option=1" name="optionslink" 
   id="optionslink" onclick="return test(this);">LINKTEXT</a>

Note that not using inline scripts at all is the best practice with javascript events.

You should read about addEventListener , you can read about it in MDN

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