亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 316 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號