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

我有一个存储在名为 的变量中的元素列表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()方法完成的,正如我在进行更多研究后发现的那样。

但是这个方法需要一个命名的外部函数——它不适用于匿名函数。所以它适用于我上面的第一个例子,但不适用于第二个例子。

所以我的问题是:如何将事件侦听器添加到元素列表中,这样我就可以做这两件事:

  1. 将参数传递给我的函数

  2. 再次移除事件监听器,稍后在代码中

谢谢你的帮助!


拉丁的传说
浏览 203回答 2
2回答

月关宝盒

您可以生成函数列表并使用它们来删除侦听器:let removers = elementList.map((el, idx) => {&nbsp; let handler = () => myFunction(idx);&nbsp; el.addEventListener('click', handler);&nbsp; return () => el.removeEventListener('click', handler);});// when you need//removers[4]();&nbsp; // calls removeEventListener

PIPIONE

要从按钮中删除事件侦听器,您需要引用函数本身。所以在使用之前addEventListener将函数存储在一个对象或一个数组中,或者你可以回顾并找到这个函数的地方。因为removeEventListener如果你不给它与你使用的完全相同的功能,它将无法工作addEventListener。在下面的代码片段中,我构建了一个存储这些事件侦听器并将其称为EventCollection. 此类用作容器并保存要添加的每个事件的列表。这样,您可以随时在代码中添加或删除所需的所有事件侦听器,而无需做太多工作。class EventCollection {&nbsp; /**&nbsp; &nbsp;* Create a list to store the entries in.&nbsp; &nbsp;*/&nbsp; constructor() {&nbsp; &nbsp; this.entries = [];&nbsp; &nbsp; this.isListening = false;&nbsp; }&nbsp; /**&nbsp; &nbsp;* Add an entry to the collection to listen for on an event.&nbsp; &nbsp;*/&nbsp; append(target, type, listener, options = false) {&nbsp; &nbsp; if (!(target instanceof EventTarget)) return;&nbsp; &nbsp; this.entries.push({ target, type, listener, options });&nbsp; &nbsp; return this;&nbsp; }&nbsp; /**&nbsp; &nbsp;* Listen for all the entries in the list.&nbsp; &nbsp;*/&nbsp; listen() {&nbsp; &nbsp; if (!this.isListening) {&nbsp; &nbsp; &nbsp; this.entries.forEach(({ target, type, listener, options }) => {&nbsp; &nbsp; &nbsp; &nbsp; target.addEventListener(type, listener, options);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; this.isListening = true;&nbsp; &nbsp; }&nbsp; &nbsp; return this;&nbsp; }&nbsp; /**&nbsp; &nbsp;* Stop listening for all the entries in the list.&nbsp; &nbsp;*/&nbsp; stopListening() {&nbsp; &nbsp; this.entries.forEach(({ target, type, listener, options }) => {&nbsp; &nbsp; &nbsp; target.removeEventListener(type, listener, options);&nbsp; &nbsp; });&nbsp; &nbsp; this.isListening = false;&nbsp; &nbsp; return this;&nbsp; }&nbsp;}// Create a new instance of an EventCollectionvar eventCollection = new EventCollection();var buttons = document.getElementsByTagName('button');function myFunction(index) {&nbsp; alert(index);}// Add all the event listeners to the collection.for (var i = 0; i < buttons.length; i++) {&nbsp; (function(i){&nbsp; &nbsp; eventCollection.append(buttons[i], 'click', function() {&nbsp; &nbsp; &nbsp; myFunction(i);&nbsp; &nbsp; }, false);&nbsp; }(i));}// Start listening.eventCollection.listen();// After 5 seconds, stop listening.// The buttons won't work anymore.setTimeout(function() {&nbsp; eventCollection.stopListening();}, 5000);<button>Button 1</button><button>Button 2</button><button>Button 3</button>像这样构建集合。用new关键字。// Create a new collectionvar eventCollection = new EventCollection();下一步是添加您要收听的事件。它需要元素、事件类型和事件触发时调用的函数。eventCollection.append(element, 'click', function() {});现在您的事件已在集合中并已存储,但它们尚未侦听事件。使用该.listen()方法循环遍历集合中的所有事件并监听它们。eventCollection.listen();每当您想停止收听集合中的事件时,请使用以下命令。eventCollection.stopListening();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript