Javascript 如何在javascript中获取此元素的innerHTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7674194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get innerHTML of this element in javascript?
提问by David
Pretty simple question. I have an element (a tag) which has an onclick to call a javascript function. Amoung other things, I want this function to echo the innerHTML of the element that called it. So, in this case, the innerHTML of the atag.
很简单的问题。我有一个元素(一个标签),它有一个 onclick 来调用一个 javascript 函数。Amoung 其他事情,我希望这个函数回显调用它的元素的innerHTML。因此,在这种情况下,是 atag 的 innerHTML。
How do I do this?
我该怎么做呢?
回答by Niet the Dark Absol
<element onClick="alert(this.innerHTML);"> ... </element>
回答by davin
markup:
标记:
<element id="foo"> ... </element>
js:
js:
document.getElementById('foo').addEventListener('click', fn);
function fn(){ alert(this.innerHTML); }
The important thing to note here, which essentially answers your question, is that the event listener when called has binds this
to the DOM node that caused the event to fire. So we can use this
in the function and it's generic. You could add another element, and bind a click listener also using fn
and the one function would work for both elements.
这里要注意的重要一点(基本上回答了您的问题)是,被调用时的事件侦听器已绑定this
到导致事件触发的 DOM 节点。所以我们可以this
在函数中使用它,它是通用的。您可以添加另一个元素,并绑定一个也使用的点击侦听器fn
,并且一个函数适用于这两个元素。