如何使用javascript在文本输入中获取html特殊字符

kli*_*kli 6 html javascript escaping special-characters htmlspecialchars

我想将一些html特殊字符发送到文本字段,然后使用javascript将其恢复为原始格式:如果我发送"&pi",它将在文本输入上显示"π",当我使用javascript时得到它,我应该得到"&pi",但我只能得到"π",而不是"&pi".请帮忙,我的代码如下:

<script type="text/javascript"> 
function qpush(a) {
    document.getElementById('input').value += a;
}

function show(a) {
    alert(document.getElementById('input').value);
}
</script>

<input type="text" id="input" />
<input type="button" onclick="qpush('&pi;');" value="&pi;" />
<input type="button" onclick="show()" value="go" />
Run Code Online (Sandbox Code Playgroud)

Lio*_*ior 3

根据您的需要,您可以执行以下 3 个选项之一:

\n\n
    \n
  1. 使用 javascript escape 和 unescape 函数:

    \n\n

    var escaped = escape(\'\xcf\x80\') // escaped = "%u03C0" unescape 会转回 \xcf\x80

  2. \n
  3. 如果你有可用的 jQuery,它的 html 方法可能可以解决问题:

    \n\n

    $(\'输入\').val().html()

  4. \n
  5. 这是一个 hack,但会起作用:按照您希望在输入元素的“data-”属性上返回的方式保存值的副本,这将在 html5 中验证,并且不会在其他文档类型中中断。

    \n\n

    document.getElementById(\'input\').setAttribute(\'data-originalValue\', \'&pi\')

  6. \n
\n