打印javascript转义文本时缺少脚本标记

时间:2016-11-04 12:04:47

标签: javascript escaping

<!DOCTYPE html>
<html>
<body>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "'Python\x20Auto\x20\x3Cscript\x20type\x3D\x22text\x2Fjavascript\x22\x3E\x20alert\x28\x22JavaScript\x20alert\x22\x29\x3B\x20\x3C\x2Fscript\x3E\x20'";
}
</script>

</body>
</html>
我将“demo”元素innerHtml设置为 Python自动警报(“JavaScript警报”)的转义版本; 即可。 如果您运行此HTML并单击“单击我”按钮。您可以将结果看作“Python Auto”。缺少脚本标记。为什么会这样?为什么脚本标记及其内容丢失?

2 个答案:

答案 0 :(得分:-1)

需要使用&amp; lt for&lt;,&amp; gt for&gt;和\&#34;为&#34;。其他一切都应该可以使用实际字符,见下文。

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "'Python Auto &ltscript type=\"text/javascript\"&gt alert(\"JavaScript alert\");&lt/script&gt'";
}
</script>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

!!!请看下面的评论,也请你的问题更清楚!!!

您可以使用\x3C而不是使用&#x3C,因为它会以某种方式转义字符串的其余部分,

<!DOCTYPE html>
<html>
<body>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "'Python\x20Auto\x20&#x3Cscript\x20type\x3D\x22text\x2Fjavascript\x22\x3E\x20alert\x28\x22JavaScript\x20alert\x22\x29\x3B\x20\x3C\x2Fscript\x3E\x20'";
}
</script>

</body>
</html>