简体   繁体   English

在Firefox中,在onclick触发器中获取锚的href

[英]In Firefox, get href of anchor in onclick trigger

With the following html: 使用以下html:

<div>
   <a href='#link1' onclick='func()' >Link 1</a>
   <a href='#link2' onclick='func()' >Link 2</a>
   <a href='#link3' onclick='func()' >Link 3</a>
</div>

function func() {
   var href = ??;
   if( href.match(/#link1/) ) {
      ...
   }
}

in Chrome (and IE?) can use this code 在Chrome(和IE?)中可以使用此代码

var href = window.event.target.href;

but window.event does not exist in Firefox 但是Firefox中不存在window.event

If the events were attached via addEventListener then could have e as an argument, but see no way to get the event passed to the onclick function when declared in html. 如果事件是通过addEventListener附加的,则可以将e作为参数,但是在用html声明时,看不到将事件传递给onclick函数的方法。

Pass in this to your function and then directly access the href property. this传递给您的函数,然后直接访问href属性。 this will refer to the element that made the call. this将涉及进行调用的元素。 You may also want to return false - this prevents the clicked link from navigating. 您可能还想返回false-这样可以防止单击链接。

http://jsfiddle.net/qjXVy/ http://jsfiddle.net/qjXVy/

function func(elem) {
    alert(elem.href);
    return false;
}

<div>
   <a href="#link1" onclick="func(this)" >Link 1</a>
   <a href="#link2" onclick="func(this)" >Link 2</a>
   <a href="#link3" onclick="func(this)" >Link 3</a>
</div>

You do get the event as an argument, in the onclick handler itself. 您确实可以在onclick处理程序本身中将事件作为参数获取。 So you can do: 因此,您可以执行以下操作:

 <a href="#link1" onclick="func(event)" >Link 1</a>

and then you can look at the event target in func . 然后您可以在func查看事件目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM