Using this in event handler in strict javascript?

半腔热情 提交于 2019-12-31 04:45:10

问题


Suppose you have a routine like the following to wire up click event handlers

getElements(".board>div").forEach(function(elem){
  elem.addEventListener("click", handleClick);
});

And then in the handler, you need to work with the sender (i.e. this)

function handleClick(){      
  if(this.innerText.toLowerCase() !== "x"){ 
    ...

How do you use this in this scenario without a jshint violation/warning?


回答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




回答2:


Why don't you just bind the function with the object?

getElements(".board>div").forEach(function(elem){
  elem.addEventListener("click", handleClick.bind(elem));
});



回答3:


use one eventhandler

especially if you have many elements inside your board.

adding multiple eventlisteners slows down the browser.

js

function h(e){
 alert(e.target.textContent)
}
document.getElementsByClassName('board')[0].onclick=h

or

document.querySelector('.board').addEventListener('click',h,false)

html

<div class="board"><div>1</div><div>2</div><div>3</div><div>4</div></div>

example

http://jsfiddle.net/3csJ2/

in your case...

function h(e){
 e.target.innerText==1||(alert('this is not 1')/*,...*/) 
}

example 2

http://jsfiddle.net/3csJ2/1/

inside the handler function (h) this is the 'board'.



来源:https://stackoverflow.com/questions/19711385/using-this-in-event-handler-in-strict-javascript

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