在文本节点内的网页上创建换行符 - Javascript

时间:2015-02-13 00:47:35

标签: javascript html line-breaks createtextnode

我已经看到了对此问题的一些回复,但这些建议并未解决我的输出问题。表单接受输入并打印到网页,如下所示:

function init() {
var div = document.createElement("div");
    div.id = "output";

var name = document.getElementById("name").value;
    name.type = "text";
var address = document.getElementById("address").value;
    address.type = "text";

    var city = document.getElementById("city").value;
        city.type = "text";
    var state = document.getElementById("state");
        state.type = "text";
        var index = state.selectedIndex;
        var fullState = state.options[index];

    var zip = document.getElementById("zip").value;
        zip.type = "text";

var email = document.getElementById("email").value;
    email.type = "text";

var areaCode = document.getElementById("areaCode").value;
    areaCode.type = "text";
var prefix = document.getElementById("prefix").value;
    prefix.type = "text";
var suffix = document.getElementById("suffix").value;
    suffix.type = "text";

var gender = document.getElementById("gender").value;

/*

var courses = document.getElementById("courses").value;
    courses.type = "text";

    var aj = document.getElementById("aj").value;
        aj.type = "text";
    var asp = document.getElementById("asp").value;
        asp.type = "text";
    var php = document.getElementById("php").value;
        php.type = "text";
*/

var br = document.createElement('br');



var printName = document.createTextNode("Name: " + name + " ");
var printEmail = document.createTextNode("Email: " + email + " ");
var printPhone = document.createTextNode("Phone: " + areaCode + "-" + prefix + "-" + suffix);
var printAddress = document.createTextNode("Address: " + address + " " + city + " " + fullState.text + " " + zip);
var printGender = document.createTextNode("Gender: " + gender + " ");
//var printCourses = document.createTextNode("Courses Taken:" + courses + " ");



div.appendChild(printName);
div.appendChild(br);
div.appendChild(printEmail);
div.appendChild(br);
div.appendChild(printPhone);
div.appendChild(br);
div.appendChild(printAddress);
div.appendChild(br);
div.appendChild(printGender);
div.appendChild(br);
//div.appendChild(printCourses);
div.appendChild(br);

var output = document.getElementById("output");

if(output) {
    output.parentNode.replaceChild(div, output);
} else {
    document.body.appendChild(div);
}
}

尽管创建了换行元素,但输出仍然只是网页上的一条连续线。还有其他建议吗?

1 个答案:

答案 0 :(得分:4)

当你这样做时

var br = document.createElement('br');

你有一个SINGLE元素的引用。所以当你这样做时:

div.appendChild(printName);
div.appendChild(br);
div.appendChild(printEmail);
div.appendChild(br);

您说&#34;添加printName元素,然后在其后添加此<br>元素。现在,创建printEmail元素,然后在其后移动相同的<br>元素。&#34;

所以最后,你还只有一个<br>元素。

可能涉及代码更改最少的修复方法如下:

function br() {
    return document.createElement('br');
}

div.appendChild(printName);
div.appendChild(br());