[英]Add JavaScript String with line breaks and tabs to HTML element
我有这个HTML:
<p id="element">Waiting for Message</p>
来自服务器的这个字符串使用JSON.stringify(),其中包含中断和制表符,即
var = "Heading (info:info) \n info: \n \t and so on "; // The actual string is more complex though, just an example
而这个Jquery将字符串发布到段落标记:
$("#element").text(data); // data is the string from the server(not in JSON!)
问题是HTML忽略了格式,但是当我使用警告框时,它会显示正确的格式。 我正在动态更新元素,因为数据来自服务器。 有什么指针吗?
您应该告诉浏览器尊重这些空白区域。 简单的方法是使用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>
利用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.