简体   繁体   中英

The this keyword in onclick handler is not working

Apologizes if it is very dumb. I cannot make this work in a click event:

<div onclick='hello()'>
     Click here!
</div>

<script>
    function hello() {
        // I want to do some works with *this* object
        alert(this.textContent);
    }
</script>    

What am I missing?

You can use .call()

The call() method calls a function with a given this value

<div onclick='hello.call(this)'></div>

 <div onclick='hello.call(this)'> Click here! </div> <script> function hello() { console.log(this.textContent); } </script> 

Or

.bind() can also be used.

The bind() method creates a new function that, when called, has its this keyword set to the provided value,

 <div onclick='hello.bind(this)()'> Click here! </div> <script> function hello() { console.log(this.textContent); } </script> 

You can use addEventListener instead of the inline handler, which I actually would recommend.

 document.querySelector('div').addEventListener('click', function() { console.log(this.textContent); }) 
 <div> Click here! </div> 


In addition to call() / bind() , you can pass the this like this as well, and simply use the passed parameter.

  <div onclick='hello(this)'> Click here! </div> <script> function hello(el) { console.log(el.textContent); } </script> 


The value of this within the handler

When attaching a handler function to an element using addEventListener() , the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.

If an event attribute (eg, onclick ) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function that binds the value of this in a manner consistent with the use of addEventListener() an occurrence of this within the code represents a reference to the element. Note that the value of this inside a function called by the code in the attribute value behaves as per standard rules .

Src: MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM