How to get innerHTML of this element in javascript?

微笑、不失礼 提交于 2019-12-05 02:24:16

问题


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.

How do I do this?


回答1:


<element onClick="alert(this.innerHTML);"> ... </element>



回答2:


markup:

<element id="foo"> ... </element>

js:

document.getElementById('foo').addEventListener('click', fn);

function fn(){ alert(this.innerHTML); }

http://jsfiddle.net/g7Bau/2/

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.



来源:https://stackoverflow.com/questions/7674194/how-to-get-innerhtml-of-this-element-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!