锚点 href 中的 Javascript:获取对“调用”锚标记的引用

Javascript in anchor href: get reference to "calling" anchor tag

本文关键字:引用 调用 中的 href Javascript 获取 锚点      更新时间:2023-09-26
<a href="javascript: get_a_reference_to_the_a_tag.doSomethingWithIt();">...

我有没有办法在不向锚标签添加 id 的情况下获取对 href javascript 中锚标签的引用?

this添加到函数调用中,但您需要onclick执行此操作,否则,this将引用Window

<a href="#" onclick="yourfunction(this)">...</a>

捷轩

您可以简单地在正在使用的函数中使用thisthis是对元素本身的引用。

编辑:看到href呼叫太晚了,我以为他正在使用onclick。无论如何,一个工作示例:

<a href="javascript:void(0);" onclick="myFunction(this);">This is the anchor tag</a>
<script>
function myFunction(anchor) {
    console.log(anchor.innerHTML); // output: This is the anchor tag
}
</script>

最好的方法是添加标识符作为类名或数据属性,您可以将其用作 javascript 的选择器(id 不是最佳实践)。如果你真的想使用你的href标签作为选择器,你可以。

.HTML:

<a href="a_link_here">

.JS:

var myAnchorTag = document.querySelector('[href=a_link_here]')
console.log(myAnchorTag) //your element
console.log(myAnchorTag.href) //'a_link_here'