从输入字段读取属性时,HTML编码丢失我正在使用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编码?
3 回答
Helenr
TA贡献1780条经验 获得超4个赞
编辑:这个答案很久以前发布了,该htmlDecode函数引入了一个XSS漏洞。它已被修改,将临时元素从a div更改为textarea减少XSS机会。但是现在,我鼓励您按照其他anwswer的建议使用DOMParser API 。
我使用这些功能:
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();}基本上,div元素在内存中创建,但它永远不会附加到文档中。
在htmlEncode函数上我设置了innerText元素,并检索编码的innerHTML; 在htmlDecode函数上我设置innerHTML元素的值并innerText检索。
在这里查看一个运行示例。
添加回答
举报
0/150
提交
取消
