我使用JavaScript从隐藏字段中拉出一个值并在文本框中显示它。隐藏字段中的值被编码。

例如,

<input id='hiddenId' type='hidden' value='chalk &amp; cheese' />

被卷入

<input type='text' value='chalk &amp; cheese' />

通过一些jQuery来获取隐藏字段的值(在这一点上,我失去了编码):

$('#hiddenId').attr('value')

问题是当我读粉笔&cheese从隐藏字段,JavaScript似乎失去了编码。我不希望价值是粉笔和奶酪。我想要字面上的amp;被保留。

是否有JavaScript库或jQuery方法可以对字符串进行html编码?


当前回答

htmlen编码给定的值

  var htmlEncodeContainer = $('<div />');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

其他回答

您不应该为了将值从一个输入字段转移到另一个输入字段而对值进行转义/编码。

<form>
 <input id="button" type="button" value="Click me">
 <input type="hidden" id="hiddenId" name="hiddenId" value="I like cheese">
 <input type="text" id="output" name="output">
</form>
<script>
    $(document).ready(function(e) {
        $('#button').click(function(e) {
            $('#output').val($('#hiddenId').val());
        });
    });
</script>

JS不会插入原始HTML或其他东西;它只是告诉DOM设置value属性(或属性;不确定)。无论哪种方式,DOM都可以为您处理任何编码问题。除非你在做一些奇怪的事情,比如使用document。写或eval, html编码将是有效透明的。

如果你正在讨论生成一个新的文本框来保存结果……还是那么简单。只需要将HTML的静态部分传递给jQuery,然后设置它返回给你的对象的其余属性/属性。

$box = $('<input type="text" name="whatever">').val($('#hiddenId').val());

据我所知,javascript中没有任何直接的HTML Encode/Decode方法。

然而,你能做的是,使用JS创建一个任意元素,设置它的内部文本,然后使用innerHTML读取它。

让我们说,使用jQuery,这应该工作:

var helper = $('chalk & cheese').hide().appendTo('body');
var htmled = helper.html();
helper.remove();

或者类似的东西。

下面是一个非jQuery版本,它比jQuery .html()版本和.replace()版本都快得多。这保留了所有空格,但与jQuery版本一样,不处理引号。

function htmlEncode( html ) {
    return document.createElement( 'a' ).appendChild( 
        document.createTextNode( html ) ).parentNode.innerHTML;
};

速度:http://jsperf.com/htmlencoderegex/17

演示:

输出:

脚本:

function htmlEncode( html ) {
    return document.createElement( 'a' ).appendChild( 
        document.createTextNode( html ) ).parentNode.innerHTML;
};

function htmlDecode( html ) {
    var a = document.createElement( 'a' ); a.innerHTML = html;
    return a.textContent;
};

document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );

//sanity check
var html = '<div>   &amp; hello</div>';
document.getElementById( 'same' ).textContent = 
      'html === htmlDecode( htmlEncode( html ) ): ' 
    + ( html === htmlDecode( htmlEncode( html ) ) );

HTML:

<input id="hidden" type="hidden" value="chalk    &amp; cheese" />
<input id="text" value="" />
<div id="same"></div>

FWIW,编码没有丢失。编码由标记解析器(浏览器)在页面加载期间使用。读取和解析源代码后,浏览器将DOM加载到内存中,编码就被解析成它所表示的内容。所以当你的JS被执行读取内存中的任何东西时,它得到的字符就是编码所表示的。

在这里,我可能严格按照语义操作,但我希望您理解编码的目的。“失去”这个词听起来像是某件事没有像它应该做的那样运作。

Underscore提供了_.escape()和_.unescape()方法来执行此操作。

> _.unescape( "chalk &amp; cheese" );
  "chalk & cheese"

> _.escape( "chalk & cheese" );
  "chalk &amp; cheese"