简体   繁体   English

无需在javascript中转义innerHTML字符?

[英]no need to escape innerHTML characters in javascript?

Should I not escape the double quotes in "markup4" and such? 我不应该逃避“markup4”中的双引号吗? To my surprize this plain works. 令我惊讶的是这个简单的作品。 If I replace them by the &quot thing it doesn't. 如果我用它没有的东西替换它们。

<script type="text/javascript">

    function test3(){
    document.getElementById('div21').innerHTML += '<div class = "markup4"><br>blablablabla1.<br><br></div><div class = "markup3"><br>blablabla2.<br><br></div>';
    }

</script>

These work without escape: 这些工作无需逃避:

innerHTML = "<div class = 'markup4'>";
innerHTML = '<div class = "markup4">';

Note: When the " used outside, the ' works properly inside. (and the opposite) 注意:当"在外面使用时, '在内部正常工作。(和相反的)

These need the escape: 这些需要逃脱:

innerHTML = '<div class = \'markup4\'>';
innerHTML = "<div class = \"markup4\">";

Note: When you use the double quote outside and inside, the inside's " needs to be escaped by \\ . (same for single quotes) 注意:当您在内部和内部使用双引号时,内部的"需要通过\\来转义。”(单引号相同)

These will break: 这些会打破:

innerHTML = "<div class = "markup4">";
innerHTML = '<div class = 'markup4'>';

First the string is parsed to an internal javascript string representation, so you first need to escape for javascript string literals. 首先,字符串被解析为内部javascript字符串表示,因此您首先需要转义为javascript字符串文字。 The result of this would be the same as what you already have - so no modification is needed. 结果将与您已有的结果相同 - 因此无需进行任何修改。

Now you have 现在你有了

<div class = "markup4"><br>blablablabla1.<br><br></div><div class = "markup3"><br>blablabla2.<br><br></div>

Internally in javascript memory. 内部在javascript内存中。

After this, it's just like you would write that as normal HTML, so of course, if you use &quot; 在此之后,就像你将它写成普通的HTML一样,当然,如果你使用&quot; it will not work. 不起作用。

It can get pretty complicated to store strings that go through 2 different interpretations, which is why you shouldn't do this but use templating engines with the templates stored in other files or custom script elements on the page, which would allow you to focus only on the html interpretation. 存储经过2种不同解释的字符串会非常复杂,这就是为什么你不应该这样做,而是使用模板引擎,将模板存储在页面上的其他文件或自定义脚本元素中,这样你就可以只关注关于html的解释。

escape should be used when you want to include quotes within the data, 当您想在数据中包含引号时,应使用escape,

ex: He said, "Please use this!" 例如:他说,“请用这个!” should get escaped like: 应该逃脱:

He said, \\" Please use this !\\". 他说,“请用这个!”。

Otherwise they work without any troubles. 否则他们没有任何麻烦。

Hope I've clarified. 希望我已经澄清了。

Don't forget browsers render their own innerHtml based on what you give them which can cause problems if nesting innerHtml code. 不要忘记浏览器根据你给出的内容渲染自己的innerHtml,如果嵌套innerHtml代码会导致问题。

I found the &apos; 我找到了&apos; and &quot; &quot; codes useful here. 代码在这里有用。

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

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