使用 val() 时特殊字符的 Javascript/jQuery 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7792362/
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
Javascript/jQuery encoding for special characters when using val()
提问by 1jr
I have a problem with special characters like &, ?, etc. and their corresponding HTML encoded writing like &
, ä
etc.
我有一个问题,特殊字符,如&,?等及其相应的HTML编码写像&
,ä
等等。
When they are used in the value tag of input fields, the browser decodes it automatically, no problem at all.
When using jQuerys val() function, the browser has no chance to evaluate the content correctly
$("button").click(function(){ $("#test").val("&"); });
当它们用于输入字段的值标签中时,浏览器会自动对其进行解码,完全没有问题。
使用 jQuery 的 val() 函数时,浏览器没有机会正确评估内容
$("button").click(function(){ $("#test").val("&"); });
Any idea?
任何的想法?
回答by Andy E
You can use this age-old entity decoding trick:
您可以使用这个古老的实体解码技巧:
$("button").click(function(){
$("#test").val($("<div>").html("&").text());
});
Working demo: http://jsfiddle.net/AndyE/XegGy/
It creates a temporary <div>
element, sets its HTML to &
and then gets the text value, which will be &
.
它创建一个临时<div>
元素,将其 HTML 设置为&
,然后获取文本值,即&
.