javascript - JS : How to concatenate variables inside appendChild()?

标签 javascript

我正在尝试将文本节点附加到段落中,其值取自其父函数的参数。

function writeText(id, value, text) {

    //create our html elements

    var body = document.body;
    var par = document.createElement("p");
        par.className = id;
    this.value = document.createTextNode(value);
    this.text = document.createTextNode(text);

    //instantiate array that we will push value and text into

    textToInsert = [];
    textToInsert.push(this.value, this.text);

    //appends this.text and this.value inside the paragraph
    //and then appends that paragraph element into the body

    par.appendChild(textToInsert.join(' :'); //this does not work!
    par.appendChild(this.value+this.text); //this does not work!
    par.appendChild(this.value); //this works!
    body.appendChild(par);       
}

这段代码给了我错误消息

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

所以我认为join()不会生成节点。如何在一个 appendChild() 中连接两个变量?

最佳答案

join 始终生成字符串。数组中的文本节点将被字符串化。

相反,您需要将纯字符串放入数组中,并仅创建一个可以附加的文本节点,其中包含您想要的串联内容。

var stringsToInsert = [value, text],
    stringToInsert = stringsToInsert.join(' :');

var textNode = document.createTextNode(stringToInsert);
par.appendChild(textNode);     

关于javascript - JS : How to concatenate variables inside appendChild()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862951/

相关文章:

javascript - 10 秒后使用 JavaScript 和表单提交重定向到另一个页面

javascript - 生成 3 个非重复值

javascript - 如何使用 JavaScript 交换表格中的图像位置?

javascript - 展开折叠树

javascript - 使用 JavaScript 进行字段验证 - onkeyup?

javascript - 无论如何,有没有办法在javascript中的不同对象之间重用键?

javascript - 将当前标签类应用到当前页面?

Javascript 对象,返回包含嵌套数组中值的更新对象

javascript - 检查我的脚本中的对象类型?

javascript - fullpage.js 最后一张幻灯片的半高