Using This In Event Handler In Strict Javascript?
Suppose you have a routine like the following to wire up click event handlers getElements('.board>div').forEach(function(elem){ elem.addEventListener('click', handleClick); })
Solution 1:
Your use of this
is valid. To suppress the this
errors in your event handler add /*jshint validthis: true */
to the top of the function.
Found that here: https://stackoverflow.com/a/16553290/552067
Solution 2:
Why don't you just bind the function with the object?
getElements(".board>div").forEach(function(elem){
elem.addEventListener("click", handleClick.bind(elem));
});
Solution 3:
use one eventhandler
especially if you have many elements inside your board.
adding multiple eventlisteners slows down the browser.
js
functionh(e){
alert(e.target.textContent)
}
document.getElementsByClassName('board')[0].onclick=h
or
document.querySelector('.board').addEventListener('click',h,false)
html
<divclass="board"><div>1</div><div>2</div><div>3</div><div>4</div></div>
example
in your case...
functionh(e){
e.target.innerText==1||(alert('this is not 1')/*,...*/)
}
example 2
inside the handler function (h) this
is the 'board'.
Post a Comment for "Using This In Event Handler In Strict Javascript?"