从输入字段读取属性时HTML编码丢失 [英] HTML-encoding lost when attribute read from input field

查看:116
本文介绍了从输入字段读取属性时HTML编码丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JavaScript从隐藏字段中提取值并将其显示在文本框中。



例如,

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

被拉进

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

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

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

问题是,当我阅读 chalk& amp; amp; amp; amp;奶酪从隐藏的领域,JavaScript似乎失去了编码。为了避免',我希望编码保留。



是否有一个JavaScript库或jQuery方法可以对字符串进行HTML编码? 使用这些函数:

 函数htmlEncode(value){
//创建一个内存中的div,设置其内部文本jQuery自动编码)
//然后将编码后的内容重新取出,div在页面上永远不会存在
return $('< div />').text(value).html( );
}

函数htmlDecode(value){
return $('< div />')。html(value).text();
}

基本上,div元素是在内存中创建的,但它永远不会附加到文档中。 / p>

htmlEncode 函数中,我设置了 innerText 元素,并检索编码的 innerHTML ;在 htmlDecode 函数中,我设置了 innerHTML va检索元素的lue和 innerText



检查正在运行的示例 here


I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,

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

gets pulled into

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

via some jQuery to get the value from the hidden field (it’s at this point that I lose the encoding):

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

The problem is that when I read chalk &amp; cheese from the hidden field, JavaScript seems to lose the encoding. To escape " and ', I want the encoding to remain.

Is there a JavaScript library or a jQuery method that will HTML-encode a string?

解决方案

I use these functions:

function htmlEncode(value){
  // Create a in-memory div, set its inner text (which jQuery automatically encodes)
  // Then grab the encoded contents back out. The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

Basically a div element is created in memory, but it is never appended to the document.

On the htmlEncode function I set the innerText of the element, and retrieve the encoded innerHTML; on the htmlDecode function I set the innerHTML value of the element and the innerText is retrieved.

Check a running example here.

这篇关于从输入字段读取属性时HTML编码丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆