在TextNode的这段代码中,我尝试使用以下代码中的\n
将字符串放在不同的行中:
var CC = function(valu, name, age){
var parent = document.createElement("div");
parent.id = valu;
parent.setAttribute("onclick", "info()");
parent.style.color = "blue";
var heading = document.createTextNode("phone no: "+valu+"\n Name:"+name+" \nAge: "+age);
parent.appendChild(heading);
var ele = document.getElementById("main");
ele.appendChild(parent);
}(valu, name, age);
然后当我尝试这个时,在行中:var heading = document.createTextNode("phone no: "+valu+"\n Name:"+name+" \nAge: "+age); \n
无效。我应该在\n
中使用TextNode
,还是以错误的方式使用它?
答案 0 :(得分:2)
问题是 document.createTextNode
会阻止文本呈现为HTML。
如果您想呈现HTML,则需要使用 document.createElement
。
要获得代码的工作演示,我必须做一些即兴创作。
我更改了以下内容:
将CC()
转换为简单函数,因为我不知道代码的其余部分是什么样的。
将valu
参数更改为phone
。不确定valu
的含义。
添加了一个全局变量id
,每次调用CC()
方法时都会递增,以便创建的div保持唯一ID。
在CC()
函数中,我创建了表示传入的每个参数的文本节点变量(名称,电话和年龄)。
将setAttribute()
更改为addEventListener()
。
我只是做了多个显示每个步骤而不是一个长appendChild()
,而每个文本节点之间都有document.createElement("br")
。
另请注意,我添加了info()
函数,该函数会警告正在点击的div信息。
var id = 1;
function info()
{
alert(this.innerText);
}
function CC (name, phone, age)
{
var parent = document.createElement("div"),
nameText = document.createTextNode("Name: " + name),
phoneText = document.createTextNode("Phone: " + phone),
ageText = document.createTextNode("Age: " + age);
parent.id = 'div' + id.toString();
parent.style.color = "blue";
parent.addEventListener("click", info, false);
parent.appendChild(nameText);
parent.appendChild(document.createElement("br"));
parent.appendChild(phoneText);
parent.appendChild(document.createElement("br"));
parent.appendChild(ageText);
parent.appendChild(document.createElement("br"));
document.getElementById("main").appendChild(parent);
id++;
}
CC('John Doe', '123.456.7890', '40');