简体   繁体   English

如何忽略引号内的标签? HTML,JavaScript

[英]How to have tags that are within quotes ignored? HTML, Javascript

Im am trying to use innerHTML to make a paragraph display. 我正在尝试使用innerHTML来显示段落。

innerHTML="<html><head></head><body></body></html>";

But I am of course getting errors because it is trying to process the tags. 但是我当然会出错,因为它正在尝试处理标签。 How can I get the browser to ignore these tags since theyre in quotes? 我如何让浏览器忽略这些标记,因为它们用引号引起了?

try: 尝试:

innerHTML="<html><head></head><body></body></html>".replace(/</g,'&lt;');

in words: replacing all < with &lt; 换句话说:将所有<替换为&lt; will trigger the browser to render &lt; 将触发浏览器呈现&lt; as string < but it [the browser] won't try to render the html-string as html. as string <但[浏览器]不会尝试将html-string呈现为html。 You could also replace all > with &gt; 您也可以将所有>替换为&gt; ofcourse. 当然。

Alternatively you can use textContent instead of innerHTML , which will escape the string directly: 或者,您可以使用textContent代替innerHTML ,这将直接转义字符串:

[yourElement].textContent = '<html><head></head><body></body></html>';

You should do escape HTML in this case. 在这种情况下,您应该转义HTML。

How about a common function: 常见功能如何:

function escape(s) {
    var el = document.createElement("div");
    el.innerText = el.textContent = s;
    s = el.innerHTML;
    return s;
}

Usage: 用法:

innerHTML = escape("<html><head></head><body></body></html>");

I think using a browser built-in behavior to escape HTML is better than trying to replace all special characters. 我认为使用浏览器的内置行为来转义HTML比尝试替换所有特殊字符更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM