[英]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="Événement"> <p>Click the button to change the placeholder text of the text field.</p> <button onclick="myFunction()">Try it</button>
Output is: "Événement"输出是:“Évé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 É
).在 HTML 中,特殊字符用
&#XXX
编码(如É
)。
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 = 'Événement from JS'; document.getElementById("myText").placeholder = a.textContent; }
<input type="text" id="myText" placeholder="Évé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.