Script tag is missing when printing a javascript e

2019-07-23 15:07发布

This question already has an answer here:

<!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>
Im setting "demo" elements innerHtml to the escaped version of Python Auto alert("JavaScript alert"); . If you run this html and click on the "Click me" button. You can see the result as "Python Auto". The script tag is missing. Why this is happening ? How come the script tag and the content of it is missing ?

2条回答
做个烂人
2楼-- · 2019-07-23 15:12

!!!Please see the comment below, also, please make your question a bit more clear!!!

Instead of using \x3C you can use &#x3C because somehow it is escaping rest of the string,

<!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>
查看更多
贪生不怕死
3楼-- · 2019-07-23 15:20

Need to use &lt for <, &gt for >, and \" for ". Everything else should be fine to use the actual characters, see below.

<!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>

查看更多
登录 后发表回答