繁体   English   中英

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

[英]JS: How to concatenate variables inside appendChild()?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM