jQuery在段落中br之前和之后的范围内包装文本 [英] jQuery wrap text in a span before and after br within a paragraph

查看:119
本文介绍了jQuery在段落中br之前和之后的范围内包装文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想知道如何在段落中br之前和之后的范围内包装文本.

As the title suggests I am wondering how I can wrap text in a span before and after br within a paragraph.

我的HTML是如此...

My HTML is as so...

<div class="blog-container">
  <div class="each-article">
    <p>Text text text <br/> text text text</p>
  </div>
  <div class="each-article">
    <p>Text text text <br/> text text text</p>
  </div>
</div>

我认为可行的jQuery是

And my jQuery, which I thought would work, is

$('.blog-container .each-article p br').before().wrap('<span></span>');

这给我的是这样的:

<div class="blog-container">
  <div class="each-article">
    <p>Text text text <br><span></span></br> text text text</p>
  </div>
  <div class="each-article">
    <p>Text text text <br><span></span></br> text text text</p>
  </div>
</div>

推荐答案

尝试一下:

http://jsfiddle.net/kKfKS/

$('.each-article p').each(function() {
    $(this).contents().filter(function() {
        return this.nodeType == 3;  
    }).wrap('<span>');
});

参考:

编辑-此处不需要修剪.但是,在某些情况下(例如,如果非文本节点是第一个子节点),可以将空白视为文本节点.看到这个小提琴: http://jsfiddle.net/M3knf/

Edit - The trim isn't necessary here. However, it looks like, in some cases (like if a non-text node is the first child), empty space can be treated as a text node. See this fiddle: http://jsfiddle.net/M3knf/

这篇关于jQuery在段落中br之前和之后的范围内包装文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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