巧转HTML实体字符

版权声明:个人笔记,不喜勿喷 https://blog.csdn.net/qq_39571197/article/details/87931759

textContext

1、具有更高的性能,不会解析HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app1">

    </div>
    <div id="app2">

    </div>
    <div id="app3">

    </div>
    <script>
        const tpl = `<div style="color:red;" onclick="alert(1);">哈哈</div>`;
        app1.innerHTML = tpl;
        app2.innerText = tpl;
        // 使用textContext将HTML转为实体
        app3.innerHTML = transHTML(tpl);


        function transHTML(html) {
            const tag = document.createElement('div');
            tag.textContent = html;
            console.log(tag.innerHTML);
            return tag.innerHTML;
        }
    </script>
</body>

</html>

 

没有更多推荐了,返回首页