简体   繁体   English

使用 &letter; JavaScript 中的符号不写希腊字母

[英]Using &letter; notation in JavaScript doesn't write greek letters

When I set an input box value with the "value" attribute in HTML to a greek letter, it shows the greek letter correctly.当我将 HTML 中具有“值”属性的输入框值设置为希腊字母时,它会正确显示希腊字母。 But when I change the "value" attribute with JavaScript, it uses the "&letter;"但是当我用 JavaScript 更改“value”属性时,它使用“&letter;” format.格式。 What can I do so that JavaScript behaves just as HTML?我该怎么做才能使 JavaScript 的行为与 HTML 一样?

HTML: <input type="text" id="input" value = "&epsilon;"> works fine. HTML: <input type="text" id="input" value = "&epsilon;">工作正常。 JavaScript: document.getElementById("input").value = "&epsilon;"; JavaScript: document.getElementById("input").value = "&epsilon;"; shows &epsilon;显示&epsilon; but not the greek letter但不是希腊字母

The problem you're facing occurs because of the way you're setting the input.您遇到的问题是由于您设置输入的方式造成的。 Javascript is (correctly) treating your &epsilon; Javascript 正在(正确地)治疗你的&epsilon; as an ordinary string, because you haven't told it that it's anything else.作为一个普通的字符串,因为你没有告诉它它是其他任何东西。

If this were an element like p , or span or any other contextual text element, you could simply do如果这是一个像pspan或任何其他上下文文本元素这样的元素,你可以简单地做

myElem.innerHTML = "&epsilon;";

However, since you want to set this to be the input's value, you can't use innerHTML , because it wouldn't make any sense.但是,由于您想将其设置为输入值,因此不能使用innerHTML ,因为它没有任何意义。 What you need to do is something like this.你需要做的是这样的事情。

 function htmlDecode(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; } document.getElementById("myInput").value = htmlDecode("&epsilon;");
 <input type="text" id="myInput" name="myInput" value="">

The function I used was originally posted in this SO answer .我使用的 function 最初发布在这个 SO answer中。 Be sure to read the rest of it, to see the other uses.请务必阅读它的 rest,以了解其他用途。

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

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