Javascript JS:如何在appendChild()中连接变量?

Javascript JS:如何在appendChild()中连接变量?,javascript,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)

我试图将一个文本节点附加到一个段落中,其值取自其父函数的参数

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);     

很抱歉,我必须编辑代码才能更彻底地解释问题。如果您试图将字符串作为子项追加,则它必须是节点