首页 > 解决方案 > 尝试使用 innerHTML 时随机发生未捕获(承诺)错误

问题描述

嗨,我在尝试通过 innerHTML 更改 html 内容时收到此错误,第一次尝试时不会发生错误,但在那之后

错误信息:

admin.js:61 Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
    at HTMLDivElement.<anonymous> (admin.js:61)
(anonymous) @   admin.js:61
async function (async)      
(anonymous)

这是代码:

const edit = async (btn) => {
    const res = await fetch(`admin/products/edit/${btn.getAttribute('id')}`)
    let product = await res.json()

    if (product) {
        $('#edit-product-modal').modal('show')
        Array.from(document.querySelectorAll('#edit-product-modal [name]')).forEach((elm) => {
            for (let i of Object.keys(product)) {
                if (elm.getAttribute('name') === i) elm.value = product[i]
            }
        })
    }

    document.querySelector('#edit-product-modal').addEventListener('submit', async (e) => {
        e.preventDefault()
        e.target.querySelector('.btn').disabled = true

        const data = { _id: null, name: null, price: null, dprice: null, description: null }

        Array.from(document.querySelectorAll('#edit-product-modal [name]')).forEach((elm) => {
            for (let i of Object.keys(data)) {
                if (elm.getAttribute('name') === i) data[i] = elm.value
            }
        })

        const res = await fetch(`admin/products/edit/${btn.getAttribute('id')}`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })

        const product = await res.json()

        btn.parentNode.parentNode.innerHTML = productHtml(product) //the error happens here
        e.target.querySelector('.btn').disabled = false
        $('.modal').modal('hide')

    })
}

标签: javascript

解决方案


推荐阅读