简体   繁体   English

如何用多行文本显示从JavaScript到HTML的文本

[英]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. 我想使用循环显示从JavaScript到HTML的多行文本。 The text position is after display the image. 文字位置在显示图像之后。 The text result should be like Place ..... // newline price .... 文本结果应类似于Place ..... //换行价格....

<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. 最干净的方法可能是执行与HTML相同的操作:将文本节点包装在<p>元素中。

Wrapping the text in an HTML element will always help you later to customize style or whatever! 将文本包装在HTML元素中将始终在以后帮助您自定义样式或其他内容!

Raw text nodes are not that convenient. 原始文本节点不是那么方便。

There are multiple ways to achieve this. 有多种方法可以实现此目的。 One is using br tags 一种是使用br标签

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 另一个可能是使用pre标签

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; 或者,您可以使用两个显示的跨度: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. 我会用一张桌子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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