javascript - 无法将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 新手,所以我不明白问题可能是什么。
解决方案
嗯,这很棘手,至少对我来说。问题是,我的两个函数的“this”不是包含它们的类,而是我试图在其上放置 onclick 的按钮,所以表达式“this.showItem”和“this.showItemEditor”没有任何意义. 我很惊讶 Firefox 没有告诉我这件事。但我很高兴一切都结束了:)
推荐阅读
- io - MPI_FILE_WRITE() 的使用
- java - 谷歌日历 API 不起作用 - 如何解决这个问题?
- python - 智能地获取两个字符之间的文本
- node.js - 如何在我的 expressJS 应用程序中获得一个喜欢的按钮?
- php - 以编程方式将可下载文件添加到 Woocommerce 产品
- javascript - 跨度jQuery的总和
- ruby-on-rails - Ruby On Rails 5 错误预期关键字_do 或 '{' 或 '('
- python - 使用返回值放入另一个函数的括号中
- javascript - 如何比较具有不同属性名称的 2 个对象数组的值?
- javascript - 通过google api验证城市是否在一个国家/地区只工作一次