2012-05-24 29 views
2

我有一个网站,其中包括jQuery的标签的HREF,所以我有一个主题标签在我的网址,获取显示所需的选项卡:JavaScript的 - 改变一个链接

www.abc.de/site#tab4 

在这个网站上我有一个链接看起来像这样:

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

有了这个链接,用户可以选择一个产品的选项。点击重新加载网站。我想做到这一点就按这个字符串在URL中的井号标签读出,然后该字符串将被添加到URL或链接后...

我的功能看起来是这样的:

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

到目前为止,该功能是点击我得到一个警报弹出窗口,显示正确的哈希标签和它的字符串。但是网站被重新加载而没有添加hashtag +字符串。它看起来像这样:

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

它应该看起来像:

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

我怎样才能得到这个工作?

+1

的了解它“的javascript:”在你的onclick是多余的 - 它应该只是测试() – Nealbo

+1

THX的提示,Nealbo! – profilneurotiker

回答

2

简单地改变位置:

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> 

另一件事,你通过当前的锚点的功能,并保存DOM查询开销:

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> 

注根本不使用inline scripts是JavaScript事件的最佳做法。

你应该阅读有关addEventListener,您可以在MDN

+0

如果它的jQuery标签我不认为它是一个好主意,返回onclick的东西你不觉得吗?特别是如果你测试函数返回false – meo

+0

@meo。你为什么这么认为? – gdoron

+0

因为返回false;打破事件的冒泡...如果其他函数监听这个元素上的klick,那么even就不会在那里得到结果 – meo

3

您没有更改href属性。尝试

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

你的代码document.getElementById("optionslink").href+info;只是没有任何影响,因为只是concatination,但没有分配给href属性。

+0

Thx Sirko为您的快速回答...我不是很熟悉javascript代码,我将不得不学习很多......将我的代码更改为您的建议对我没有任何影响,但第二种解决方案gdoron为我做了... thx了! – profilneurotiker