如何对可能具有 html 标签的文本进行 HTML 编码,而不用 Javascript 对标签本身进行编码
基本上我有一些文本可能包含 HTML 标签,但也可能包含非 HTML 编码字符。
var doc = window.document.implementation.createDocument
('http://www.w3.org/1999/xhtml', 'html', null);
var text = '<head><script>somejs</script>' +
'<script>var x = 7; var y = 5; var foo = x < y;</script>' +
'</head><body></body>');
我希望将文本设置为元素的 innerHTML 属性。如果我这样做,
doc.getElementsByTagName('html')[0].innerHTML = text;
由于 x 和 y 之间的小于号,这会导致 INVALID_STATE_ERR: DOM Exception 11 。
但是,如果我对我得到的变量文本进行 htmlEncode
<head><script>somejs</script><script>var x = 7; var y = 5; var foo = x < y;</script></head><body></body>
,因此我会丢失元素在设置了 insideHTML 后按预期行为所需的所有标签。是否有任何标准方法可以对字符串中所有标签的内容进行 html 编码,而不对标签本身进行编码?
Basically I have some text that may contain HTML tags but may also contain non-HTML encoded characters.
var doc = window.document.implementation.createDocument
('http://www.w3.org/1999/xhtml', 'html', null);
var text = '<head><script>somejs</script>' +
'<script>var x = 7; var y = 5; var foo = x < y;</script>' +
'</head><body></body>');
I wish to set text to an elements innerHTML attribute. If I just do
doc.getElementsByTagName('html')[0].innerHTML = text;
This causes a INVALID_STATE_ERR: DOM Exception 11 because of the less than sign between x and y.
However, if I htmlEncode the variable text I get
<head><script>somejs</script><script>var x = 7; var y = 5; var foo = x < y;</script></head><body></body>
And thus I lose all the tags which I need for the element to behave as desired once its innerHTML has been set. Is there any standard way to htmlencode the contents of all the tags in a string without encoding the tags themselves?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于内联脚本 您需要在后面跟有空格字符时转义字符串
,
>
或/
,否则它将关闭相应的开始标记。
因此,您可以使用
<\/script>
,而不是。这有效:
更新:现在您已经编辑了您的问题,我发现您正在使用 XHTML!这就解释了它 -
innerHTML
在 XHTML 中不起作用。For inline scripts you need to escape the string
</script
when followed by a space character,>
, or/
, else it would close the respective opening tag.So, instead of
</script>
, you could use<\/script>
. This works:Update: Now that you’ve edited your question, I see you’re using XHTML! That explains it —
innerHTML
doesn’t work in XHTML.