如何包装以< br>< Br>分隔的文本节点用自己的< p>标签? [英] How can I wrap text nodes separated by <br><Br> with their own <p> tags?

查看:135
本文介绍了如何包装以< br>< Br>分隔的文本节点用自己的< p>标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有内容从Web服务返回,我无法修改该返回的数据,例如:

I've got content coming back from a webservice I cannot modify that returns data such as:

<div id="entrance" style="">
    Habilitação / Diploma de Ensino Medio Diploma de Ensino Pre Universitario 
    <br>
    <br>
    Diploma Record of study 
</div>

如何将两个句子分别包装为< p>使用jQuery的标签?我知道我可以使用.wrap,但是这样可以包装全部内容.我需要RegEx吗?

How can I wrap the two sentences in separate < p > tags using jQuery? I know I could use .wrap but that would wrap the entire contents. Do I need a RegEx?

谢谢, 托马斯

更新:

我的要求更改为需要列表而不是段落,因此使用下面的答案,我对其进行了少许修改以包装在<中. li>然后是整个< ul>

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 >

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/

我的代码将所有非空文本节点转换为包含该文本的段落.所有其他类型的节点都将被删除.

My code transforms all non-empty text-nodes to paragraphs containing that text. All other types of nodes are removed.

这篇关于如何包装以&lt; br&gt;&lt; Br&gt;分隔的文本节点用自己的&lt; p&gt;标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆