简体   繁体   中英

How to display text with multiline from JavaScript to the HTML

I want to display multi line text, from JavaScript to the HTML using looping. The text position is after display the image. The text result should be like Place ..... // newline price ....

<div id="display">
            <script type="text/javascript" src="../controler/package.js"></script>
</div>


var display = document.getElementById('display');

function  buildImages(images,place,k,price){
 var last=document.createElement("IMG");
    last.src=images;
    last.width=800;
    last.height=600;
    last.style.marginTop=30;
    display.appendChild(last);

    var x = document.createElement("H3");
    var t = document.createTextNode("Place:"+place);
    var z = document.createTextNode(" price:"+price);
    x.appendChild(t);
    x.appendChild(z);
    display.insertBefore(x,display.childNodes[k]);

The cleanest way is probably to do the same thing you would do in HTML: wrap your text nodes in <p> elements.

Wrapping the text in an HTML element will always help you later to customize style or whatever!

Raw text nodes are not that convenient.

There are multiple ways to achieve this. One is using br tags

var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place);
var br = document.createElement("BR");
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(br);
x.appendChild(z);

Another could be using a pre tag

var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place + "\n price:" + price);
x.appendChild(t);

Or you could could use two spans that have display: block;

var x = document.createElement("H3");
var t = document.createElement("SPAN");
t.style.display = "block";
t.innerText = "Place:" +place;
var z = document.createElement("SPAN");
z.style.display = "block";
z.innerText = "Price:" +price;
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(z);

It can not work like this by design. if you do not use

 <pre> 

or

 <code> 

if you want to use line feeds or if you prefer other tags like

 <p>

then you has to use at least

  <br> 

by this you can still format the text as you wish. Will look usually a bit messy. I would use a table.

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