为了账号安全,请及时绑定邮箱和手机立即绑定

在 div 中显示 <script> 标签

在 div 中显示 <script> 标签

青春有我 2023-05-19 19:52:18
我需要在 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 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

你可以使用这个功能:


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>


查看完整回答
反对 回复 2023-05-19
  • 1 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信