eventListener被正确分配,但不会触发函数



我有一个名为ContextMenu的类,它用来替换浏览器在右键单击页面时显示的默认上下文菜单。

此菜单需要将一些eventListener应用于其子菜单。

<div id="contextmenu" class="hidden">
<ul>
<li id="download-file" class="action">Download</li>
<li id="rename-file" class="action">Rename</li>
<li id="delete-file" class="action">Delete</li>
<li id="details-file" class="action">Details</li>
</ul>
</div>

这是上下文菜单的html

export default class ContextMenu
{
contextMenu
events
actions
selectedItem
constructor(HTMLContextMenu)
{
this.contextMenu = HTMLContextMenu
window.document.onmousedown = (event) => this.show(event)
this.events = ['click', 'touchstart']
this.actions = window.document.querySelectorAll('.action') // all elements that have to trigger an eventListener have the class "action"
for (const event in this.events)
{
this.actions[0].addEventListener(event, this.download, false)
this.actions[1].addEventListener(event, this.rename, false)
this.actions[2].addEventListener(event, this.delete, false)
this.actions[3].addEventListener(event, this.details, false)
}
this.selectedItem = null
}

这是javascript,我没有粘贴整个类,只是与问题相关。正如您所看到的,for in循环处理总共应用8个侦听器的eventListeners。问题是,每当我点击元素时,什么都不会发生

正如iQucik所说,您在循环中使用了错误的关键字。如果您使用的是可迭代对象,则必须使用关键字中的,否则,对于可枚举对象,请使用中的<strong。>

一些参考文献:

循环的MDN文档:。。

循环中的MDN文档:。。在中

export default class ContextMenu
{
contextMenu
events
actions
selectedItem
constructor(HTMLContextMenu)
{
this.contextMenu = HTMLContextMenu
window.document.onmousedown = (event) => this.show(event)
this.events = ['click', 'touchstart']
this.actions = window.document.querySelectorAll('.action') // all elements that have to trigger an eventListener have the class "action"
for (const event of this.events)
{
this.actions[0].addEventListener(event, this.download, false)
this.actions[1].addEventListener(event, this.rename, false)
this.actions[2].addEventListener(event, this.delete, false)
this.actions[3].addEventListener(event, this.details, false)
}
this.selectedItem = null
}
<div id="contextmenu" class="hidden">
<ul>
<li id="download-file" class="action">Download</li>
<li id="rename-file" class="action">Rename</li>
<li id="delete-file" class="action">Delete</li>
<li id="details-file" class="action">Details</li>
</ul>
</div>

我发现了这个问题。for(this.events中的const事件(循环是错误的,它必须是for(this.events的const event(才能使其工作。

for (const event of this.events)
{
this.actions[0].addEventListener(event, this.download, false)
}

最新更新