【问题标题】:how to append a string with appendChild in javascript如何在javascript中使用appendChild附加字符串
【发布时间】: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


【解决方案1】:

appendChild 需要 Node 或元素。你有两个选择:

创建元素:

input=document.createElement("input");
input.type="date";
input.className="input-date";
input.value=user.date;
input.hidden=true;

或使用innerHTML。当然它会替换el 的内容,但你可以使用占位符或虚拟元素。

var div=document.createElement("div");
div.innerHTML="<input ...";
input=div.children[0];

我会做第一件事。或者如果你想写得更少,也可以使用框架,但这有点矫枉过正。

【讨论】:

  • 我期待找到一种更简单的方法来做到这一点,但我必须这样做。谢谢!
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 2014-08-18
  • 1970-01-01
  • 2011-01-26
  • 2019-11-28
  • 2013-07-18
相关资源
最近更新 更多