javascript - 使用 fetch api 和 express.js 后,我的按钮无法正常工作
问题描述
我对请求在客户端页面上显示模板的按钮有奇怪的问题。
这是客户端代码。整个类的主要任务是使用户能够单击按钮,发送请求并使用已从把手模板呈现的 HTML 获取响应,并将其粘贴到客户端的特定位置。它有效,但只有一次。在第一次单击并显示元素后,我完全失去了与这些按钮的任何交互。没有请求,甚至没有可供点击的EventListener。我没有错误。点击后完全没有任何反应。
class Weapons {
constructor() {
this.buttons = document.querySelectorAll('.type')
}
async displayWeapon(path) {
const container = document.querySelector('.shop-container')
await fetch(`weapons/${path}`).then(response => response.json()).then(data => container.innerHTML += data);
}
chooseWeapon() {
this.buttons.forEach(btn => {
btn.addEventListener('click', (e) => {
console.log('click');
let weaponType = e.target.dataset.type
switch (weaponType) {
case 'pistols':
console.log('click');
return this.displayWeapon(weaponType)
case 'rifles':
console.log('click');
return this.displayWeapon(weaponType)
case 'grenades':
console.log('click');
return this.displayWeapon(weaponType)
case 'closerange':
console.log('click');
return this.displayWeapon(weaponType)
case 'rocketlauchner':
console.log('click');
return this.displayWeapon(weaponType)
}
})
})
}
}
document.addEventListener('DOMContentLoaded', function () {
const weapons = new Weapons();
weapons.chooseWeapon();
> When I invoke displayWeapon(path) here it also works, but immidiately
> after displaying html elements clicking on buttons again does not
> initiate any action.
})
这是 app.get 函数,但我怀疑它是问题的根源。
app.get('/weapons/:id', (req, res) => {
console.log('req');
console.log(req.url);
let type = req.params.id;
res.render(type, function (err, html) {
res.json(html);
})
})
解决方案
行。答案其实很简单。在 fetch 函数container.innerHTML += data.
中这一行删除了我的带有按钮的 html,同时它删除了 eventListeners。所以我只需要修改我的html。
推荐阅读
- java - 如何解释在 SRTP 实现中计算 AES 计数器模式的 IV 的符号
- javascript - 如何检测用户是否正在输入以及他使用 python 或电子 js 输入的内容?
- cypress - 如何从 cypress 上的 support/commands.js 访问环境变量?
- java - Android Java Pjsip - 重新邀请后的单向音频
- typescript - tsconfig.json 抱怨相对路径
- django - 从 django 小部件 FilteredSelectMultiple 中删除搜索选项
- tensorflow - 使用神经网络进行文本分类时,准确性和损失之间是否存在直接关系?
- excel - 如何复制包含文档超链接的单元格并将其放入新行的表格列中
- makefile - Makefile:5:目标“运行”的配方失败
- prolog - Prolog列表操作函数