我有一个具有本地 href 值的锚标记,以及一个使用 href 值但将其定向到与通常情况略有不同的位置的 JavaScript 函数。标签看起来像
<a onclick="return follow(this);" href="sec/IF00.html"></a>
和一个看起来像的 JavaScript 函数
baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
location.href = baseURL + item.href;
}
我希望 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 字段可能或者可能没有子目录(例如 href="page.html"
与 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
就我而言,我有一个带 # 的 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
});
此代码适用于我获取文档的所有链接
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
href 属性设置或返回链接的 href 属性的值。
var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
var url="https://www.google.com/";
console.log( url+hello);
document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html
不定期副业成功案例分享