Javascript 为什么我的“<br />”标签被转换为“<br />”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7353718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are my "<br />" tags getting converted to "<br />"?
提问by jini
I have HTML data stored in database which I wish to display as is. It keeps converting
tags to <br />
which is a behavior I do not want. I have tried playing with javascript replace and still I am unable to convert it to regular HTML.
我在数据库中存储了 HTML 数据,我希望按原样显示。它不断将
标签转换为<br />
我不想要的行为。我曾尝试使用 javascript 替换,但仍然无法将其转换为常规 HTML。
var venueaddress = msg.result[0].venueaddress;
var venueaddress2 = venueaddress.replace("[newline]", "<br />");
alert(venueaddress2); //shows <br />
$("#venueaddress").text(venueaddress2); //lets now display it on the browser
<li><h3>Venue Address</h3><p><strong> <span id="venueaddress"></span> </strong></p></li>
However when it renders on browser, it has the <br /> and there fore there is no line break.
但是,当它在浏览器上呈现时,它具有 <br /> 并且因此没有换行符。
采纳答案by Senad Me?kin
Your problem is with
你的问题是
$("#venueaddress").text(venueaddress2);
you should use
你应该使用
$("#venueaddress").html(venueaddress2);
Text will encode any html character and will display it in span as encoded, html will not.
文本将对任何 html 字符进行编码,并将其显示为已编码的跨度,而 html 则不会。
回答by Icarus
<br />
== <br />
You just need to Decodethe output to get back the original HTML.
<br />
==<br />
您只需要对输出进行解码即可恢复原始 HTML。
回答by Quentin
Presumably because when you are inserting it into the DOM, you are inserting it as text and not as HTML.
大概是因为当你将它插入到 DOM 中时,你是将它作为文本而不是 HTML 插入。
Since you haven't show the code you are using to do that, it is hard to say for sure, or to say what the best way to change it so it expects HTML would be.
由于您尚未显示用于执行此操作的代码,因此很难肯定地说,或者说更改它以便期望 HTML 的最佳方法是什么。
回答by Juan Pablo Ugas
You can also replace the chars with the actual <br/>
tag.
您还可以用实际<br/>
标签替换字符。
myString.replace(/<br>/g, '<br/>')
回答by Larry K
Your html data is being "escaped." This prevents people from sending the <script>
tag to unsuspecting people at their browser.
您的 html 数据正在“转义”。这可以防止人们将<script>
标签发送给浏览器中毫无戒心的人。
Fix: first you'll need to determine if your issue is a "bug" or a "feature."
修复:首先,您需要确定您的问题是“错误”还是“功能”。
Escaping html is usually a good thing. Especially if the only issue is one of presentation.
转义 html 通常是一件好事。特别是如果唯一的问题是演示文稿之一。
For example, a work around might be to insert newline characters rather than the br element.
例如,解决方法可能是插入换行符而不是 br 元素。