2011-11-12 41 views
3

我想根據HR標記從不同的DIV中的Web服務接收到的文章(= HTML內容)。使用基於HR標記的Javascript/JQuery拆分HTML中的HTML

我用一個例子來解釋,這是我從服務接收:

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

我要打的基礎上,HR-標籤:

<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(或用另一種方法;-))來做到這一點?

回答

6

採用分體式創建和陣列和環通創建的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

+0

謝謝!它很棒! – benske

+0

Oke這是接受知道(我不知道這個選項:-)) – benske

+0

但你最好小心拼寫變化,如'


','
'等。一個正則表達式會導致變化更穩健。查看此答案的示例:http://stackoverflow.com/a/40115509/263832 – xr280xr

1

嘗試 -

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); 

這將只是刪除所有的<hr/>當時的追加剩餘contnet到page.Which我認爲會達到你想要的東西,而不執行split。你可以做這樣的拆分 -

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

這將給你一個數組,其中包含您在問題中列出的HTML的兩個位。您可以使用添加到您的網頁 -

$.each(htmlarr,function (index,value) { 
    $('body').append(value); 
}); 

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