我正在为学校做作业。我一切正常。唯一错误的是如何格式化输出。我不明白为什么我会收到格式化的输出。我正在使用javascript,并且正在创建节点并将其附加为子元素。我的主要目标是将每条信息格式化并放在各自的行中。这是我的javascript函数。
function createUserid()
{
var firstString = window.prompt ( "Enter first name", "" );
//documentwrite
var lower = firstString.toLowerCase();
// firstString.substring(0,4)
// firstString.concat
var lastString = window.prompt ( "Enter last name", "" );
var lowlast = lastString.toLowerCase();
var socialString = window.prompt ( "Enter social security number without dashes", "" );
var ln = lowlast.substring(0,4); //first 4 of last name
var ls = socialString.substring(5,9); //last 4 of social
var fs = socialString.substring(0,5); //first 5 of social
var fn = lower.substring(0,4); //first 4 of first name
//var user = docoument.write("<p>" + "Username: " + lastString +
//var pass = <p>"Password: " +
//var myDiv = document.getElementById('here');
//myDiv.innerHTML = ____ ;
var e = document.getElementById('info');
var o = document.getElementById('here');
//creating 2 elements: p, br
var newPara = document.createElement('p');
var tBR = document.createElement('br');
//prepare text nodes
var first = document.createTextNode('First name: ' + firstString);
var last = document.createTextNode('Last name: ' + lastString);
var social = document.createTextNode('Social Security #: ' + socialString);
var userN = document.createTextNode('Username: ' + ln + ls);
var passW = document.createTextNode('Password: ' + fs + fn);
//put together paragraph
newPara.appendChild(first);
newPara.appendChild(tBR);
newPara.appendChild(last);
newPara.appendChild(tBR);
newPara.appendChild(social);
newPara.appendChild(tBR);
newPara.appendChild(userN);
newPara.appendChild(tBR);
newPara.appendChild(passW);
//insert into div id of info
document.getElementById('info').appendChild(newPara);
o.style.display = 'none';
e.style.display = 'block';
}
这是我收到的输出
这就是输出的外观。
最佳答案
您一次又一次地附加相同的节点。
newPara.appendChild(first);
newPara.appendChild(tBR);
newPara.appendChild(last);
newPara.appendChild(tBR); <--- this node gets moved, since you append it again.
newPara.appendChild(social);
newPara.appendChild(tBR);
newPara.appendChild(userN);
newPara.appendChild(tBR); <--- this is where tBR will be at last.
newPara.appendChild(passW);
而是这样做:
var first = document.createTextNode('First name: ' + firstString + '<br/>');
或这个 :
newPara.appendChild(first);
newPara.appendChild(document.createElement('br'));
newPara.appendChild(last);
newPara.appendChild(document.createElement('br'));
.................................
此处的文档:
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild