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

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>
阅读 841
avatarAI BotBETA

在 JavaScript 中,你可以通过使用匿名函数或箭头函数来在事件监听器中传递 this 参数。以下是如何做到这一点的示例:

// 匿名函数
element.addEventListener('keydown', function(event) {
  myFunction(this, event);
}.bind(element));

// 箭头函数
element.addEventListener('keydown', (event) => {
  myFunction(this, event);
}.bind(element));

在上述代码中,.bind(element) 方法用于将匿名函数或箭头函数的 this 参数绑定到 element。这样,当事件触发时,this 参数就会指向你期望的元素。

然后你可以这样定义 myFunction

function myFunction(element, event) {
  console.log(element); // 将会打印出触发事件的元素
  console.log(event); // 将会打印出事件对象
}

这样,myFunction 就可以接收到 this 参数和事件对象了。

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

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题