Mic*_*utz 100 html javascript href
我有一个具有本地href值的锚标记,以及一个使用href值的JavaScript函数,但将它指向一个与通常不同的地方.标签看起来像
<a onclick="return follow(this);" href="sec/IF00.html"></a>
Run Code Online (Sandbox Code Playgroud)
和一个看起来像的JavaScript函数
baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
location.href = baseURL + item.href;
}
Run Code Online (Sandbox Code Playgroud)
我希望item.href只返回一个短的字符串"sec/IF00.html",而是返回完整的href,"http://www.thecurrentdomain.com/sec/IF00.html".有没有办法我可以拉出锚<a>标签中的短href ?或者我通过自然的HTML行为失去了它?
我想我可以使用字符串操作来执行此操作,但它变得棘手,因为我的本地页面实际上可能是"http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html",并且我的href字段可能或者可能没有子目录(对于ex href="page.html"vs. href="sub/page.html"),所以我不能总是在最后一个斜杠之前删除所有东西.
你可能想知道为什么我要求这个,这是因为它只会使页面更清洁.如果不可能只得到短的href(如在锚<a>标签中那样),那么我可能只是在标签中插入一个额外的字段,比如link="sec/IF00.html",但是再次,这会有点麻烦.
aor*_*sik 212
下面的代码获取完整路径,锚点指向:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
Run Code Online (Sandbox Code Playgroud)
而下面的一个获取href属性的值:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
Run Code Online (Sandbox Code Playgroud)
document.getElementById("link").getAttribute("href");
如果您有多个<a>标记,例如:
<ul>
<li>
<a href="1"></a>
</li>
<li>
<a href="2"></a>
</li>
<li>
<a href="3"></a>
</li>
</ul>Run Code Online (Sandbox Code Playgroud)
你可以这样做:document.getElementById("link")[0].getAttribute("href");访问第一个<a>标签数组,或取决于你的条件.
该代码适用于我获取文档的所有链接
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
Run Code Online (Sandbox Code Playgroud)
就我而言,我有一个带有 # 的 href,并且 target.href 返回了完整的 url。Target.hash 为我完成了这项工作。
$(".test a").on('click', function(e) {
console.log(e.target.href); // logs https://www.test.com/#test
console.log(e.target.hash); // logs #test
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220726 次 |
| 最近记录: |