将string 的字符串转换为HTML的两种要领

将string 的字符串转换为HTML的两种要领

  1. 采纳jquery对象转换

  2. 采纳原生javascript中DOMParser的parseFromString要领完成

1.采纳jquery完成

    var str="<div>"
                +"<div id='div1'>"
                    +"<div id='div1_1'>div1-1</div>"
                    +"<div id='div1_2'>div1-2</div>"
                +"</div>"
                +"<div id='div2'>"
                    +"<div id='div2_1'>div2-1</div>"
                    +"<div id='div2_2'>div2-2</div>"
                +"</div>";
              +"/div>";
    var divHtml=$(str).find('#div1').html();
    console.log(divHtml);        

输出效果

<div id="div1_1">div1-1</div><div id="div1_2">div1-2</div>

2. 采纳DOMParser完成

    var str="<div>"
            +"<div id='div1'>"
                +"<div id='div1_1'>div1-1</div>"
                +"<div id='div1_2'>div1-2</div>"
            +"</div>"
            +"<div id='div2'>"
                +"<div id='div2_1'>div2-1</div>"
                +"<div id='div2_2'>div2-2</div>"
            +"</div>";
          +"/div>";
    var parser = new DOMParser();
    var doc=parser.parseFromString(str, "text/xml");
    console.log(doc.getElementById('div1'). innerHTML);

输出效果为

<div id="div1_1">div1-1</div><div id="div1_2">div1-2</div>
    原文作者:keeping_action
    原文地址: https://segmentfault.com/a/1190000004975637
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞