如何在事件监听器中传递 'this' 参数?

作者站长头像
站长
· 阅读数 26

addEventListener('keydown', myFunction),removeEventListener('keydown', myFunction)

怎么在myFunction传参数 this?

function myFunction(_this){
  console.log(_this)
}

解决方法:

<body>
  <button onclick="onRemoveEventListener()">removeEventListener</button>
  <div class="container">123</div>
  <script>

    // 点击事件函数
    const eventClickFunc = (e) => {
      handleDivClick(e, this)
    }

    const container = document.querySelector('.container')
    container.addEventListener('click', eventClickFunc)

    // 监听 click
    function handleDivClick(e, _this) {
      console.log(e.target, _this);
    }

    // 取消监听 click
    function onRemoveEventListener() {
      console.log(1);
      const container = document.querySelector('.container')
      container.removeEventListener('click', eventClickFunc)
    }

  </script>

</body>
回复
1个回答
avatar
test
2024-06-23
<input type="text" id="i" />
<script type="text/javascript">
  function myFunction(_this, e) {
    console.log(_this, e);
  }
  document.querySelector("#i").addEventListener("keydown", function (event) {
    myFunction(this, event);
  });

</script>

answer image

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容