在 div 中显示 <script> 标签

我需要在 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/


青春有我
浏览 169回答 1
1回答

人到中年有点甜

你可以使用这个功能:function htmlencode(str) {&nbsp; &nbsp; return str.replace(/[&<>"']/g, function($0) {&nbsp; &nbsp; &nbsp; &nbsp; return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";&nbsp; &nbsp; });}并按以下方式使用它:function htmlencode(str) {&nbsp; &nbsp; return str.replace(/[&<>"']/g, function($0) {&nbsp; &nbsp; &nbsp; &nbsp; return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";&nbsp; &nbsp; });}document.getElementById("myDiv").innerHTML = htmlencode('<scrip t>alert("hi")</scrip t>')<div id="myDiv"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript