English 中文(简体)
javascript - 改变链接的刻度
原标题:javascript - changing href of a link

我有一个网站 包括jQuery-Tabs, 所以我有一个标签在我的 URL 显示一个想要的标签 :

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;
}

到目前为止, 函数都在点击上, 我得到了一个提示式的显示, 显示正确的标签标签和字符串 。 但是网站会重新加载而不添加标签+string 。 它看起来像 :

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

它应该看起来像:

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

我怎么能让这个工作?

最佳回答

简单地更改位置:

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 脚本 是javascript 事件的最佳做法。

您应该阅读有关addEventLististener 的内容,您可以在MDN 中读到有关它的内容。

问题回答

您没有更改 href 属性。 尝试

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

您的代码 document. getEplementById (“ optionslink”).href+info; 只是没有效果, 因为只有连接符, 但对 href 属性没有指定 。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签