【问题标题】:Using this in event handler in strict javascript?在严格的javascript事件处理程序中使用这个?
【发布时间】:2013-11-11 17:54:31
【问题描述】:

假设您有如下例程来连接点击事件处理程序

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

然后在处理程序中,您需要与发送者(即 this)一起工作

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

在这种情况下如何使用 this 而没有 jshint 违规/警告?

【问题讨论】:

  • 为什么不向 .board 添加一个处理程序?
  • 为什么 JSHint 认为 this 不好?
  • 不是 jshint 本身说“这个”不好。只是 jshint 建议你 "use strict" 并且在严格模式下,方法调用之外的 this 总是绑定到 undefined

标签: javascript this jshint strict


【解决方案1】:

使用一个事件处理程序

特别是如果你的板子中有很多元素。

添加多个事件监听器会降低浏览器的速度。

js

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

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

html

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

例子

http://jsfiddle.net/3csJ2/

在你的情况下......

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

示例 2

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

在处理函数 (h) this 内部是“板”。

【讨论】:

    【解决方案2】:

    为什么不直接将函数与对象绑定呢?

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

    【讨论】:

      【解决方案3】:

      您对this 的使用是有效的。要在事件处理程序中抑制 this 错误,请将 /*jshint validthis: true */ 添加到函数顶部。

      在这里找到:https://stackoverflow.com/a/16553290/552067

      【讨论】:

        猜你喜欢
        • 2022-11-30
        • 2022-08-13
        • 1970-01-01
        • 1970-01-01
        • 2016-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多