[英]How can I HTML encode text that may have html tags without encoding the tags themselves in Javascript
Basically I have some text that may contain HTML tags but may also contain non-HTML encoded characters. 基本上,我有一些文本可能包含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>');
I wish to set text to an elements innerHTML attribute. 我希望将文本设置为一个元素innerHTML属性。 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. 由于x和y之间的小于号,这将导致INVALID_STATE_ERR:DOM异常11。
However, if I htmlEncode the variable text I get 但是,如果我对可变文本进行htmlEncode,则会得到
<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. 因此,一旦设置了innerHTML,我就失去了元素所需的所有标记,这些标记才能使元素表现出所需的行为。 Is there any standard way to htmlencode the contents of all the tags in a string without encoding the tags themselves?
有没有一种标准的方法可以对字符串中所有标签的内容进行html编码而不对标签本身进行编码?
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 . 对于内联脚本,当后跟一个空格字符
>
或/
,需要转义字符串</script
,否则它将关闭相应的开始标记 。
So, instead of </script>
, you could use <\\/script>
. 因此,代替
</script>
您可以使用<\\/script>
This works: 这有效:
var text = '<head><script>somejs<\/script><script>var x = 7; var y = 5; var foo = x < y;<\/script></head><body></body>';
el.innerHTML = text;
Update: Now that you've edited your question, I see you're using XHTML! 更新:现在,您已经编辑了问题,我看到您正在使用XHTML! That explains it —
innerHTML
doesn't work in XHTML. 这就解释了–
innerHTML
在XHTML中不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.