从anchor(a)标签获取本地href值 [英] Get local href value from anchor (a) tag

查看:85
本文介绍了从anchor(a)标签获取本地href值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有本地href值的定位标记,以及一个使用href值的JavaScript函数,但将它指向与通常情况不同的地方。标签看起来像

 < a onclick =return follow(this); HREF = 秒/ IF00.html >< / A> 

和一个类似于

  baseURL ='http://www.someotherdomain.com/'; 
函数跟随(item){
location.href = baseURL + item.href;
}

我期望 item.href 只会返回一小段sec / IF00.html,但它会返回完整的href,http&#x3a; // www.thecurrentdomain.com/sec/IF00.html。有没有一种方法可以将锚点< a> 标签中的short href取出?或者我是否会因自然的HTML行为而失去它?



我想我可以使用字符串操作来做到这一点,但它会变得棘手,因为我的本地页面实际上可能是http #x3a; // www.thecurrentdomain.com/somedir/somepath/sec/IF00.html,我的href字段可能有也可能没有子目录(例如 href =page.html vs. href =sub / page.html),所以我不能总是在最后一个斜杠前删除所有东西。



您可能想知道我为什么要这样做,这是因为它会让页面变得更干净。如果无法获得短href(如放在锚点< a> 标记中),那么我可能只需在标记中插入一个额外的字段,比如 link =sec / IF00.html,但是,这样做会有点混乱。解决方案

下面的代码获取完整路径,其中的锚点:

  document.getElementById AAA)HREF。 // http://example.com/sec/IF00.html 

href 属性的值:

  document.getElementById(aaa ).getAttribute(的 href); // sec / IF00.html 


I have an anchor tag that has a local href value, and a JavaScript function that uses the href value but directs it to a slightly different place than it would normally go. The tag looks like

<a onclick="return follow(this);" href="sec/IF00.html"></a>

and a JavaScript function that looks like

baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
    location.href = baseURL + item.href;
}

I would expect that item.href would just return a short string of "sec/IF00.html", but instead it returns the full href, "http://www.thecurrentdomain.com/sec/IF00.html". Is there a way that I can pull out just the short href as put in the anchor <a> tag? Or do I lose that by natural HTML behavior?

I suppose I could use a string manipulation to do this, but it gets tricky because my local page may actually be "http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html", and my href field may or may not have a subdirectory in it (for ex href="page.html" vs. href="sub/page.html"), so I cannot always just remove every thing before the last slash.

You may wonder why I am requesting this, and it is because it will just make the page a lot cleaner. If it is not possible to get just the short href (as put in the anchor <a> tag), then I could probably just insert an extra field into the tag, like link="sec/IF00.html", but again, that would be a little messier.

解决方案

The below code gets the full path, where the anchor points:

document.getElementById("aaa").href; // http://example.com/sec/IF00.html

while the one below gets the value of the href attribute:

document.getElementById("aaa").getAttribute("href"); // sec/IF00.html

这篇关于从anchor(a)标签获取本地href值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆