我正在尝试将文本节点附加到段落中,其值取自其父函数的参数。
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/