Javascript 无法将EventListener添加到随EventListener一起添加的按钮
我有两个函数,可以通过单击按钮重新绘制页面的一部分,每个函数在渲染后都应该向绘制的按钮添加一个eventlistenerJavascript 无法将EventListener添加到随EventListener一起添加的按钮,javascript,html,events,dom-events,addeventlistener,Javascript,Html,Events,Dom Events,Addeventlistener,我有两个函数,可以通过单击按钮重新绘制页面的一部分,每个函数在渲染后都应该向绘制的按钮添加一个eventlistener showItem () { const Id = this.dataset.product_id; const ItemBlock = document.getElementById(Id) const Template = renderItemNormalView(); const HTML = Tem
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);
}
首次通过单击调用函数showItemEditor时,但在呈现页面后,showItem不会作为onclick添加。我是js新手,所以我不明白问题可能是什么。嗯,至少对我来说,这是个棘手的问题。问题是,对于这两个函数,“this”不是包含它们的类,而是我试图单击的按钮,因此表达式“this.showItem”和“this.showItemEditor”毫无意义。我很惊讶firefox没有告诉我这件事。但我很高兴一切都结束了:)