简体   繁体   English

将包含换行符和制表符的JavaScript字符串添加到HTML元素

[英]Add JavaScript String with line breaks and tabs to HTML element

I have this HTML: 我有这个HTML:

<p id="element">Waiting for Message</p>

And this string from the server using JSON.stringify() with breaks and tabs in it ie 来自服务器的这个字符串使用JSON.stringify(),其中包含中断和制表符,即

var = "Heading (info:info) \n info: \n \t and so on "; // The actual string is more complex though, just an example

And this Jquery to post the string to the paragraph tag: 而这个Jquery将字符串发布到段落标记:

$("#element").text(data); // data is the string from the server(not in JSON!)

The problem is the HTML ignores the formatting but when I use an alert box it displays with the proper formatting. 问题是HTML忽略了格式,但是当我使用警告框时,它会显示正确的格式。 I am dynamically updating the element as data comes from the server. 我正在动态更新元素,因为数据来自服务器。 Any pointers? 有什么指针吗?

You should tell browser to respect those whitepaces. 您应该告诉浏览器尊重这些空白区域。 Easy way to do it is using white-space: pre rule: 简单的方法是使用white-space:pre rule:

 var data = "Heading (info:info) \\n info: \\n \\t and so on "; $("#element").html(data); 
 #element { white-space: pre; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="element">Waiting for Message</p> 

Make use of the pre tag in HTML and update your text there 利用HTML中的pre tag并在那里更新您的文本

 $(document).ready(function(){ var data = { "id": "1", "nome": "erwrw", "cognome": "sdsfdfs", "CF": "qwert", "eta": "27", "sesso": "uomo", "indirizzo": "qwerrt", "luogo": "wewrw", "provincia": "ewrewrw", "citta": "erwrwr", "comune": "ewrewrw" } var obj = JSON.stringify(data, null, 4); $('#element').text(obj); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre id="element">Waiting for Message</pre> <button id="btn">send</button> 

$("#element").html(data.replace(/(\n)/g, '<br>'));

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

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