首页 > 解决方案 > 使用 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);
    })
})

标签: javascriptnode.jsexpress

解决方案


行。答案其实很简单。在 fetch 函数container.innerHTML += data.中这一行删除了我的带有按钮的 html,同时它删除了 eventListeners。所以我只需要修改我的html。


推荐阅读