How to get innerHTML of this element in javascript?

后端 未结 2 1551
旧时难觅i
旧时难觅i 2021-01-01 04: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

相关标签:
2条回答
  • 2021-01-01 04:27

    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 讨论(0)
  • 2021-01-01 04:40
    <element onClick="alert(this.innerHTML);"> ... </element>
    
    0 讨论(0)
提交回复
热议问题