在div中显示<script>标签

时间:2020-10-18 04:31:27

标签: javascript jquery

我需要在div中显示用户输入。但是,如果用户放入标签,它将执行脚本标签中的所有内容。

例如

<html>
<body>
    <button onclick="runTest('<script>alert(\'test\')</script>')">Click Me</button>
    <div id="test"></div>
</body>
</html>

还有我的javascript runTest函数

function runTest(str) {
    $('#test').append($('<div>' + str + '</div>'));
}

如果我运行此命令,它将导致alert()被执行。我尝试使用escape(str),但它显示了转义字符%3Cscript%3Ealert%28%27test%27%29%3C/script%3E

有什么主意吗?这是提琴手:https://jsfiddle.net/zvLg1w6q/1/

谢谢...

1 个答案:

答案 0 :(得分:1)

您可以使用此功能:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}

并按如下方式使用它:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}

document.getElementById("myDiv").innerHTML = htmlencode('<scrip t>alert("hi")</scrip t>')
<div id="myDiv">

</div>