为了账号安全,请及时绑定邮箱和手机立即绑定

如何将可移动事件侦听器添加到元素列表,但仍将参数传递给它调用的函数?

如何将可移动事件侦听器添加到元素列表,但仍将参数传递给它调用的函数?

拉丁的传说 2022-06-09 16:14:34
我有一个存储在名为 的变量中的元素列表elementList,并希望为每个元素添加一个事件侦听器。所以我创建了以下循环:for (i = 0; i < elementList.length; i++) {  elementList[i].addEventListener('click', myFunction, false);}问题?我需要i作为参数传递给myFunction. 在网上做了一些研究后,我找到了这个解决方案:for (i = 0; i < elementList.length; i++) {  elementList[i].addEventListener('click', (function(i){    return function(){      myFunction(i);    };  }(i)), false);}代码运行良好——但仍然存在问题。稍后在我的代码中,我需要再次删除事件侦听器,这是通过该removeEventListener()方法完成的,正如我在进行更多研究后发现的那样。但是这个方法需要一个命名的外部函数——它不适用于匿名函数。所以它适用于我上面的第一个例子,但不适用于第二个例子。所以我的问题是:如何将事件侦听器添加到元素列表中,这样我就可以做这两件事:将参数传递给我的函数再次移除事件监听器,稍后在代码中谢谢你的帮助!
查看完整描述

2 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

您可以生成函数列表并使用它们来删除侦听器:


let removers = elementList.map((el, idx) => {

  let handler = () => myFunction(idx);

  el.addEventListener('click', handler);

  return () => el.removeEventListener('click', handler);

});


// when you need

//

removers[4]();  // calls removeEventListener


查看完整回答
反对 回复 2022-06-09
?
PIPIONE

TA贡献1829条经验 获得超9个赞

要从按钮中删除事件侦听器,您需要引用函数本身。所以在使用之前addEventListener将函数存储在一个对象或一个数组中,或者你可以回顾并找到这个函数的地方。因为removeEventListener如果你不给它与你使用的完全相同的功能,它将无法工作addEventListener。


在下面的代码片段中,我构建了一个存储这些事件侦听器并将其称为EventCollection. 此类用作容器并保存要添加的每个事件的列表。这样,您可以随时在代码中添加或删除所需的所有事件侦听器,而无需做太多工作。


class EventCollection {


  /**

   * Create a list to store the entries in.

   */

  constructor() {

    this.entries = [];

    this.isListening = false;

  }


  /**

   * Add an entry to the collection to listen for on an event.

   */

  append(target, type, listener, options = false) {

    if (!(target instanceof EventTarget)) return;

    this.entries.push({ target, type, listener, options });

    return this;

  }


  /**

   * Listen for all the entries in the list.

   */

  listen() {

    if (!this.isListening) {

      this.entries.forEach(({ target, type, listener, options }) => {

        target.addEventListener(type, listener, options);

      });

      this.isListening = true;

    }

    return this;

  }


  /**

   * Stop listening for all the entries in the list.

   */

  stopListening() {

    this.entries.forEach(({ target, type, listener, options }) => {

      target.removeEventListener(type, listener, options);

    });

    this.isListening = false;

    return this;

  } 


}


// Create a new instance of an EventCollection

var eventCollection = new EventCollection();


var buttons = document.getElementsByTagName('button');


function myFunction(index) {

  alert(index);

}


// Add all the event listeners to the collection.

for (var i = 0; i < buttons.length; i++) {

  (function(i){

    eventCollection.append(buttons[i], 'click', function() {

      myFunction(i);

    }, false);

  }(i));

}


// Start listening.

eventCollection.listen();


// After 5 seconds, stop listening.

// The buttons won't work anymore.

setTimeout(function() {

  eventCollection.stopListening();

}, 5000);

<button>Button 1</button>

<button>Button 2</button>

<button>Button 3</button>


像这样构建集合。用new关键字。


// Create a new collection

var eventCollection = new EventCollection();

下一步是添加您要收听的事件。它需要元素、事件类型和事件触发时调用的函数。


eventCollection.append(element, 'click', function() {});

现在您的事件已在集合中并已存储,但它们尚未侦听事件。使用该.listen()方法循环遍历集合中的所有事件并监听它们。


eventCollection.listen();

每当您想停止收听集合中的事件时,请使用以下命令。


eventCollection.stopListening();


查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 202 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号