【问题标题】:Wrap text within element在元素内换行
【发布时间】:2012-11-30 19:52:14
【问题描述】:

我需要用 span 将文本包装在 div 中。

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

试过了,但它并没有真正起作用......

$('.item').text().wrap('<span class="new" />'); 

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以使用contents().eq() 来完成此操作

    $('.item').each(function(i, v) {
        $(v).contents().eq(2).wrap('<span class="new"/>')
    });​
    

    http://jsfiddle.net/qUUbW/

    【讨论】:

    • .eq(2) 替换为 .filter(function() { return this.nodeType === 3; }) 以定位文本节点,无论其在元素中的位置如何。
    【解决方案2】:

    怎么样

    $('.item').contents().filter(function(){
        return this.nodeType == 3 && $.trim(this.nodeValue).length;
    }).wrap('<span class="new" />');
    

    http://jsfiddle.net/mowglisanu/x5eFp/3/

    【讨论】:

    • 我正要发布几乎相同的东西,您可以通过将$.trim($(this).text()).length替换为$.trim(this.nodeValue) != ''来优化它
    • 我注意到  在 div 中也被包裹了......而@wirey的解决方案没有。感谢您的帮助。
    【解决方案3】:

    单DIV

    var txt = $('.count')[0].nextSibling;
    $(txt).wrap('<span class="new" />');
    

    JSfiddle

    多个 DIV

    var markers = document.querySelectorAll('.count'),
        l = markers.length,
        i, txt;
    
    for (i = l - 1; i >= 0; i--) {
        txt = markers[i].nextSibling;
        $(txt).wrap('<span class="new" />');
    }
    

    JSFiddle

    【讨论】:

    【解决方案4】:

    我对此的看法:

    $('.item').contents().each(function() {
        if (this.nodeType == 3 && $.trim(this.nodeValue) != '') {
           $(this).wrap('<span class="textwrapped"></span>');
        }
    });
    

    $.trim 部分是必需的,因为用于缩进 html 代码的选项卡也是我们必须过滤掉的文本节点(例如,&lt;span class="count"&gt; 之前的选项卡)

    查看工作demo

    【讨论】:

      【解决方案5】:
      $('.item').html($('<span class="new">').text($(".item").text()))
      

      【讨论】:

      • 这不会将他的文本节点包装在一个跨度内......以及#id是什么 - 他有类等 - 使用这些。
      【解决方案6】:

      如果您需要在元素内包装文本内容,请使用 wrapInner

      https://api.jquery.com/wrapInner/

      示例 html

      <div class="item">contents inside needs to be wrapped</div>`
      
      // jQuery
      $('.item').wrapInner('<span></span>')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-23
        • 2011-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多