【问题标题】:Split HTML in divs with Javascript/JQuery based on HR tags使用基于 HR 标签的 Javascript/JQuery 在 div 中拆分 HTML
【发布时间】:2011-12-27 13:23:01
【问题描述】:

我想根据 HR 标签将我从 Web 服务收到的文章(= HTML 内容)拆分到不同的 DIV 中。

我用一个例子来解释,这是我从服务中得到的:

<p>This is an article bla bla</p> <hr/> <p>this is the next page of the article blabla ...</p>

我想根据 HR-tag 制作:

<div><p>This is an article bla bla</p></div>
<div><p>this is the next page of the article blabla ...</p></div>

我尝试了不同的想法,但不起作用。我如何使用 Javascript 或 JQuery(或使用其他方法 ;-))来做到这一点?

【问题讨论】:

    标签: javascript jquery html split


    【解决方案1】:

    使用 split 创建数组并循环创建 div。

    var html = "<p>This is an article bla bla</p> <hr/> <p>this is the next page of the article blabla ...</p>";
    
    
    $(html.split('<hr/>')).each(function(){
        $('#test').append('<div>'+this+'</div>')
    })
    

    Demo

    【讨论】:

    • 但您最好注意拼写变体,例如“
      ”、“
      ”等。考虑变体的正则表达式会更加健壮。例如,请参阅此答案:stackoverflow.com/a/40115509/263832
    【解决方案2】:

    试试-

    var html = '<p>This is an article bla bla</p> <hr/> <p>this is the next page of the article blabla ...</p>'
    var htmlarr = html.split('<hr/>');
    html = html.replace(/<hr\/>/g,'');
    $('body').append(html);
    

    这只会删除所有 &lt;hr/&gt;s 然后将剩余的 contnet 附加到页面。我认为这将实现您想要的,而无需执行 split。您可以像这样进行拆分-

    var htmlarr = html.split('<hr/>');
    

    这会给您留下一个数组,其中包含您在问题中列出的两位 HTML。您可以使用 -

    将其添加到您的页面
    $.each(htmlarr,function (index,value) {
       $('body').append(value); 
    });
    

    演示 - http://jsfiddle.net/cCR34/2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 2013-10-27
      • 1970-01-01
      相关资源
      最近更新 更多