我使用 JavaScript 从隐藏字段中提取一个值并将其显示在文本框中。隐藏字段中的值被编码。
例如,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
被拉入
<input type='text' value='chalk & cheese' />
通过一些 jQuery 从隐藏字段获取值(此时我丢失了编码):
$('#hiddenId').attr('value')
问题是当我读到chalk & cheese
从隐藏字段来看,JavaScript 似乎失去了编码。我不希望该值是chalk & cheese
。我要的是字面意思amp;
被保留。
是否有 JavaScript 库或 jQuery 方法可以对字符串进行 HTML 编码?
EDIT:这个答案是很久以前发布的,htmlDecode
函数引入了 XSS 漏洞。它已被修改,将临时元素从div
to a textarea
减少 XSS 机会。但现在,我鼓励您使用 DOMParser API,如其他答案 https://stackoverflow.com/a/34064434/5445.
我使用这些功能:
function htmlEncode(value){
// Create a in-memory element, set its inner text (which is automatically encoded)
// Then grab the encoded contents back out. The element never exists on the DOM.
return $('<textarea/>').text(value).html();
}
function htmlDecode(value){
return $('<textarea/>').html(value).text();
}
基本上,textarea 元素是在内存中创建的,但它永远不会附加到文档中。
On the htmlEncode
函数我设置了innerText
的元素,并检索编码innerHTML
;于htmlDecode
函数我设置了innerHTML
元素的值和innerText
被检索到。
检查一个正在运行的例子here http://jsbin.com/ejuru.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)