[英]How can I wrap text nodes separated by <br><Br> with their own <p> tags?
我有從Web服務返回的內容,我無法修改該返回的數據,例如:
<div id="entrance" style="">
Habilitação / Diploma de Ensino Medio Diploma de Ensino Pre Universitario
<br>
<br>
Diploma Record of study
</div>
如何使用jQuery將兩個句子包裝在單獨的<p>標記中? 我知道我可以使用.wrap,但是這樣可以包裝全部內容。 我需要RegEx嗎?
謝謝托馬斯
更新:
我的要求更改為需要列表而不是段落,因此使用下面的答案,我對其進行了少許修改,將其包裝在<li>中,然后將整個內容包裝在<ul>中
jQuery('#entrance').show();
jQuery('#entrance').html(data).contents().each(function () {
if ( this.nodeType === 3 ) jQuery( this ).wrap( '<li />' );
else jQuery( this ).remove();
});
jQuery('#entrance').wrapInner('<ul />');
怎么樣:
$( '#entrance' ).contents().each(function () {
if ( this.nodeType === 3 && $.trim( this.data ) !== '' ) {
$( this ).wrap( '<p />' );
} else {
$( this ).remove();
}
});
現場演示: http : //jsfiddle.net/ZMD6m/5/
我的代碼將所有非空文本節點轉換為包含該文本的段落。 刪除所有其他類型的節點。
此方法使用$(this).text()
查找每個子元素的長度。 如果為零,則將其刪除,否則將其包裝在一個段落中:
$('#entrance').contents().each(function(i,el) {
if ($.trim($(this).text()).length) {
$(this).wrap('<p>');
} else {
$(this).remove();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.