This question already has answers here:
Can scripts be inserted with innerHTML?
                                
                                    (18个回答)
                                
                        
                3年前关闭。
            
        



<!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”。脚本标记丢失。为什么会这样呢?为什么脚本标记及其内容丢失了?

最佳答案

需要将&lt用于,并将\“用于”。其他所有内容都可以使用实际字符,请参见下文。



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

09-11 20:37