【问题标题】:It is not possible to addEventListener to the button added with the EventListener无法将EventListener 添加到使用EventListener 添加的按钮
【发布时间】:2020-11-09 22:38:10
【问题描述】:

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

    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 新手,所以我不明白问题可能是什么。

【问题讨论】:

    标签: javascript html events dom-events addeventlistener


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2021-07-24
      相关资源
      最近更新 更多