javascript - 尝试使用 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')
})
}
解决方案
推荐阅读
- gradle - 任何 gradle 项目中默认存在哪个 gradle 任务?
- javascript - 通过在状态中自动计算将数字乘以 10 - React JS
- swift - 如何在集合视图中从 sqlite 数据库中获取数据时快速解决 iOS 中的内存问题
- javascript - 页面中的加载栏
- influxdb - 将数据从一个保留策略移动到另一个 Influx DB
- mysql - 生成一百万个随机数,但长度为 4
- javascript - 如何在javascript中获取父iframe id
- java - 错误:应为 BEGIN_ARRAY,但在第 1 行第 1 列路径 $
- html - 如何仅使用 css 为搜索栏设置动画并保持输入为用户输入打开?
- c# - 无法从 xamarin 表单 ios 应用程序中的根页面导航到页面