[英]How can I wrap text nodes separated by <br><Br> with their own <p> tags?
I've got content coming back from a webservice I cannot modify that returns data such as: 我有从Web服务返回的内容,我无法修改该返回的数据,例如:
<div id="entrance" style="">
Habilitação / Diploma de Ensino Medio Diploma de Ensino Pre Universitario
<br>
<br>
Diploma Record of study
</div>
How can I wrap the two sentences in separate < p > tags using jQuery? 如何使用jQuery将两个句子包装在单独的<p>标记中? I know I could use .wrap but that would wrap the entire contents.
我知道我可以使用.wrap,但是这样可以包装全部内容。 Do I need a RegEx?
我需要RegEx吗?
Thanks, Thomas 谢谢托马斯
UPDATE: 更新:
My requirements changed to needing a list instead of paragraphs so using the answer below, I modified it slightly to wrap in < li > and then the whole thing in a < ul > 我的要求更改为需要列表而不是段落,因此使用下面的答案,我对其进行了少许修改,将其包装在<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 />');
How about: 怎么样:
$( '#entrance' ).contents().each(function () {
if ( this.nodeType === 3 && $.trim( this.data ) !== '' ) {
$( this ).wrap( '<p />' );
} else {
$( this ).remove();
}
});
Live demo: http://jsfiddle.net/ZMD6m/5/ 现场演示: http : //jsfiddle.net/ZMD6m/5/
My code transforms all non-empty text-nodes to paragraphs containing that text. 我的代码将所有非空文本节点转换为包含该文本的段落。 All other types of nodes are removed.
删除所有其他类型的节点。
This approach uses $(this).text()
to find the length of each sub-element. 此方法使用
$(this).text()
查找每个子元素的长度。 If it's zero, it's removed, otherwise it's wrapped in a paragraph: 如果为零,则将其删除,否则将其包装在一个段落中:
$('#entrance').contents().each(function(i,el) {
if ($.trim($(this).text()).length) {
$(this).wrap('<p>');
} else {
$(this).remove();
}
});
http://jsfiddle.net/mblase75/ZMD6m/3/ http://jsfiddle.net/mblase75/ZMD6m/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.