首页 > 解决方案 > 无法将EventListener 添加到使用EventListener 添加的按钮

问题描述

我有两个函数可以通过单击一个按钮来重绘页面的一部分,每个函数在渲染后都应该向绘制的按钮添加一个事件监听器。

    showItem () {
        const Id = this.dataset.product_id;
        const ItemBlock = document.getElementById(Id)
        const Template = renderItemNormalView();
        const HTML = Template(ItemBlock.dataset);
        ItemBlock.innerHTML = HTML;
        const editBtn = ItemBlock.querySelector('.js-edit-item');
        editBtn.addEventListener('click', this.showItemEditor);
    }

    showItemEditor () {
        const id = this.dataset.product_id;
        const itemBlock = document.getElementById(id);
        const template = renderItemEditView();
        const HTML = template(itemBlock.dataset);
        itemBlock.innerHTML = HTML;
        const saveChanges = itemBlock.querySelector('.js-save-item-changes');
        saveChanges.addEventListener('click', this.showItem);
    }

第一次通过click调用函数showItemEditor,但是渲染一个页面后,showItem没有添加为onclick。我是 js 新手,所以我不明白问题可能是什么。

标签: javascripthtmleventsdom-eventsaddeventlistener

解决方案


嗯,这很棘手,至少对我来说。问题是,我的两个函数的“this”不是包含它们的类,而是我试图在其上放置 onclick 的按钮,所以表达式“this.showItem”和“this.showItemEditor”没有任何意义. 我很惊讶 Firefox 没有告诉我这件事。但我很高兴一切都结束了:)


推荐阅读