最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - How to get innerHTML of this element in javascript? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Oct 6, 2011 at 12:34 David asked Oct 6, 2011 at 12:23 DavidDavid 16.7k35 gold badges109 silver badges168 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11
<element onClick="alert(this.innerHTML);"> ... </element>

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.

发布评论

评论列表(0)

  1. 暂无评论