使用val()时特殊字符的Javascript/jQuery编码

编程入门 行业动态 更新时间:2024-10-10 08:24:16
本文介绍了使用val()时特殊字符的Javascript/jQuery编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对特殊字符(如& ;、ä等)及其相应的HTML编码文字(如&,ä等)有疑问.

I have a problem with special characters like &, ä, etc. and their corresponding HTML encoded writing like &, ä etc.

  • 在输入字段的value标记中使用它们时,浏览器会自动对其进行解码,完全没有问题.

  • When they are used in the value tag of input fields, the browser decodes it automatically, no problem at all.

使用jQuerys val()函数时,浏览器没有机会正确评估内容

When using jQuerys val() function, the browser has no chance to evaluate the content correctly

$("button").click(function(){ $("#test").val("&"); });

有什么主意吗?

推荐答案

您可以使用这个古老的实体解码技巧:

You can use this age-old entity decoding trick:

$("button").click(function(){ $("#test").val($("<div>").html("&amp;").text()); });

正在运行的演示: jsfiddle/AndyE/XegGy/

它将创建一个临时的<div>元素,将其HTML设置为&amp;,然后获取文本值,该文本值将为&.

It creates a temporary <div> element, sets its HTML to &amp; and then gets the text value, which will be &.

更多推荐

使用val()时特殊字符的Javascript/jQuery编码

本文发布于:2023-11-27 18:38:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特殊字符   val   jQuery   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!