且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 23:47:16

!!!请参见下面的评论,也请让您的问题更清楚! >

您可以使用&#x3C 代替使用 \x3C >因为某种原因它在转义字符串的其余部分,所以

 <!DOCTYPE html> 
< html>
< body>

< p>单击按钮以触发一个函数,该函数将在带有id = demo的p元素中输出 Hello World。

< button onclick = myFunction()>点击我< / 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>


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

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