我有这个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忽略了格式化,但是当我使用警告框时,它会显示正确的格式。我正在动态更新元素,因为数据来自服务器。有什么指针吗?
答案 0 :(得分:7)
您应该告诉浏览器尊重这些空白区域。简单的方法是使用white-space: pre规则:
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>
答案 1 :(得分:4)
利用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>
答案 2 :(得分:1)
$("#element").html(data.replace(/(\n)/g, '<br>'));