简体   繁体   中英

Add line break to HTML from Js loop

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \\n escape character, but it didn't do anything. Any help would be appreciated.

function generateIDs() 
{

var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;

for (var x=0;x<num;x++) 
{

var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;


}


    <form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>

<p id="numbers">

</p>

\\n doesn't mean much to a browser; use <br/> instead.

Example:

// snip
for (var x=0;x<num;x++) 
{
    var id = Math.floor((Math.random()*10000)+1);
    par.innerHTML = id.toString() + '<br/>';       
}
//snip

Note that this is going to overwrite the previous value on each iteration. You probably want this:

par.innerHTML += id.toString() + '<br/>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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