我可以从一个Javascript方法中找出谁的DOM元素叫我吗? [英] Can I find out from a Javascript method, who\which DOM element called me?
问题描述
<a onclick ="foo()" href="bar.html" >Link </a>
<script>
...
function foo(){
//I want to know the href property of whoever called me.
//something like this.caller.href ??
}
</script>
我想我可以分配所有元素ID,然后将自己的ID传递给JS方法, m调用,但我正在寻找一个更好的方式。
I guess I could just assign all element IDs and then pass my own ID to the JS method I'm calling, but I was looking for a better way.
推荐答案
当浏览器调用一个函数作为DOM事件的结果JavaScript将对象传递给包含事件信息的函数。但是IE在其他方面的工作方式有所不同。要在所有浏览器中工作, foo()
应该引用一个参数*(我使用 e
):
When the browser calls a function as the result of a DOM event, JavaScript passes an object to that function which contains information about the event. But it works a little differently in IE than others. To work in all browsers, foo()
should take an argument* (I use e
):
function foo(e) {
var sender = (e && e.target) || (window.event && window.event.srcElement);
//sender is the DOM element which was clicked
alert(sender.href); //assumes the clicked element was an <a>
}
第一行将分配sender元素的值,事件在所有浏览器中。
The first line will assign "sender" the value of the element which originated the event in all browsers.
现在,如果您的< a>
包含元素(例如图像)和那些之一是点击的实际元素,则该元素将成为发件人。如果这是可能的话,你需要从发件人走走DOM,直到找到你的链接:
Now, if your <a>
contains child elements (for example, an image) and one of those was the actual element clicked, then that element will become the "sender". If this is a possibility, you need to walk up the DOM from the sender until you find your link:
function foo(e) {
var sender = (e && e.target) || (window.event && window.event.srcElement);
//sender is the DOM element which was clicked
var myEle = sender;
//find the parent node until we hit the <a>
while(myEle.tagName.toUpperCase() != 'A') {
myEle = myEle.parentNode;
}
//myEle is now the <a>. sender is still the originator.
alert(myEle.href);
}
*您还可以访问传递给函数的任何参数,即使它们是未声明,通过使用参数[]
数组。
*You can also access any arguments passed to the function, even if they are not declared, by using the arguments[]
array.
这篇关于我可以从一个Javascript方法中找出谁的DOM元素叫我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!