简体   繁体   English

由 javascript 设置的占位符文本不解码 HTML 编码的特殊字符

[英]Placeholder text set by javascript not decoding HTML encoded special characters

When setting placeholder text via javascript, special characters are not displaying properly.通过 javascript 设置占位符文本时,特殊字符无法正确显示。

 function myFunction() { document.getElementById("myText").placeholder = "Événement"; }
 <input type="text" id="myText" placeholder="&#201;v&#233;nement"> <p>Click the button to change the placeholder text of the text field.</p> <button onclick="myFunction()">Try it</button>

Output is: "&#201;v&#233;nement"输出是:“&#201;v&#233;nement”

Expected output: "Événement"预期输出:“Événement”

Looking for a javascript solution where I can convert any text containing any encoded character.寻找一个 javascript 解决方案,我可以在其中转换包含任何编码字符的任何文本。

In HTML, special characters are encoded with &#XXX (Like &#201 ).在 HTML 中,特殊字符用&#XXX编码(如&#201 )。

In Javascript, special characters are encoded with \\uXXXX (Like )在 Javascript 中,特殊字符用\\uXXXX编码(如

Check https://en.wikipedia.org/wiki/List_of_Unicode_characters for the list of escape code.检查https://en.wikipedia.org/wiki/List_of_Unicode_characters以获取转义码列表。

In your case, it would be在你的情况下,这将是

document.getElementById("myText").placeholder = "\Év\ènement";

The most straightforward way to convert is to create an element, set your HTML entity as innerHTML and get textContent, something like this:最直接的转换方法是创建一个元素,将 HTML 实体设置为 innerHTML 并获取 textContent,如下所示:

 function myFunction() { let a = document.createElement('span'); a.innerHTML = '&#201;v&#233;nement from JS'; document.getElementById("myText").placeholder = a.textContent; }
 <input type="text" id="myText" placeholder="&#201;v&#233;nement"> <p>Click the button to change the placeholder text of the text field.</p> <button onclick="myFunction()">Try it</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM