使用 jQuery/JavaScript 警告特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14622769/
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
Alerting Special Characters using jQuery/JavaScript
提问by Chamara Keragala
How do i display a string with Special Characters like € in a Javascript/jQuery alert?
如何在 Javascript/jQuery 警报中显示带有特殊字符(如 €)的字符串?
eg: I want to display a message box with "The Price is 10"
例如:我想显示一个带有“价格为 10”的消息框
But when i use the below code:
但是当我使用以下代码时:
alert("The Price is €10");
The Output shown in the message box is "The Price is €10"
, I want my output to be "The Price is 10"
.
消息框中显示的输出是"The Price is €10"
,我希望我的输出是"The Price is 10"
.
Can some help me with this please? Thanks in advance.
有人可以帮我吗?提前致谢。
回答by Riju Mahna
Use this as the alert. Works fine for me.
将此用作警报。对我来说很好用。
alert(' The Price is \u20AC 10');
The description is here : http://leftlogic.com/projects/entity-lookup/
回答by techfoobar
The native alert
method does not decode HTML encoded entities.
本机alert
方法不解码 HTML 编码的实体。
But browsers do while rendering HTML. One hack is to create a HTML element with the specific text as its innerHTML
(so it does the character processing), then get back its text
property and alerting it out.
但是浏览器在渲染 HTML 时会这样做。一种技巧是创建一个带有特定文本的 HTML 元素innerHTML
(因此它进行字符处理),然后取回它的text
属性并警告它。
function alertSpecial(msg) {
msg = $('<span/>').html(msg).text();
alert(msg);
}
alertSpecial('The Price is €10');
This will work for all &xxx characters that the browser can display, without needing to find out the character code for each special character you may want to use.
这将适用于浏览器可以显示的所有 &xxx 字符,而无需找出您可能想要使用的每个特殊字符的字符代码。