js如何把html当字符串渲染到页面上

JavaScript010

js如何把html当字符串渲染到页面上,第1张

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<script>标签,输入js代码:var a = '<input type="text" value="test" />'document.body.innerText = a。

3、浏览器运行index.html页面,此时html代码被当成字符串渲染到了页面上。

function html2Escape(sHtml) { 

    return  sHtml.replace(/[<>&"']/g, function(c){

            return {'<':'&lt','>':'&gt','&':'&amp','"':'&quot',"'":'&apos'}[c]

        }) 

}

 

// 其中{}是键值对的对象,c是属性,就是<>&"'这些,根据其中某个找到对应的html的字符

 

// html字符转义