【发布时间】:2020-09-06 07:04:44
【问题描述】:
我需要加载一些数据并以两种方式将其插入li。首先,它作为<p> 插入。其次,它作为具有指定值的隐藏输入插入。我怎样才能做到这一点?我的意思是,如果我用 innerHTML 属性来做,它可以工作,但我需要添加 2 个元素,而不仅仅是一个。当我尝试使用appendChild 时,它给出了错误:
infoPersonal.js:22 Uncaught (in promise) TypeError: Failed to execute 'Node' 上的 'appendChild':参数 1 不是 'Node' 类型。
我能做什么?
编辑:在下面的代码中,它仅在满足条件时输入,但应该使用每个 el 添加输入
const datos= () => {
const token = localStorage.getItem('token')
if (token) {
return fetch('https://janfa.gharsnull.now.sh/api/auth/me', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization : token,
},
})
.then( x => x.json())
.then( user =>{
const datalist = document.querySelectorAll(".data")
datalist.forEach( function(el){
var input
const template = '<p>' + user[el.getAttribute("data-target")] + '</p>'
if (el.getAttribute("data-target")==="birth") {
input = `<input class="input-date" type ="date" value="${user[date]}" hidden>`
}
el.innerHTML=template //this works
el.appendChild(input) //this doesn't
})
})
}
}
window.onload=() =>{
datos()
}
【问题讨论】:
-
考虑查看
document.createElement的文档 - 成功调用此函数的结果是您可以与.appendChild一起使用 -
THIS 回答你的问题了吗?
-
是的,我只是确保没有更简单的方法可以做到这一点,谢谢你们!
标签: javascript html innerhtml appendchild