使用jquery拆分节点元素

时间:2013-09-25 01:58:27

标签: javascript jquery html

我的html文字如下:

  <p>
     Sample <span style="font-weight:bold"> code .... [upto 100 characters]</span>
     <i>italic content</i>
  </p>

我想输出为

  <p>
     Sample <span style="font-weight:bold"> code .... [upto 80 characters]</span>
  </p>
  <p>
     <span style="font-weight:bold">
         [remaining 20 characters]
     </span>
     <i>italic content</i>
  </p>

因为我只需要显示90个文字字符。有时候我会在内容中获得元素,所以我需要准确地打破节点元素并正确渲染。

任何人都可以使用jquery帮助我如何做到这一点。

先谢谢。

3 个答案:

答案 0 :(得分:1)

尝试

$('p').each(function () {
    var $span = $(this).children('span');
    var text = $span.text();
    $span.text(text.substring(0, 80));
    if (text.length > 80) {
        $('<p />').append($('<span />', {
            text: text.substring(80),
            style: 'font-weight:bold'
        })).append($(this).find('i')).insertAfter(this)
    }
})

演示:Fiddle

答案 1 :(得分:0)

将元素ID添加到示例代码&amp;径流跨度,用css设计它们

 <style>
    #sample-code { font-weight: bold };
    #run-off {font-weight: bold };
 </style>

 <p>
     Sample <span id="sample-code"> code .... [upto 80 characters]</span>
 </p>
 <p>
    <span id="run-off">
     [remaining 20 characters]
    </span>
    <i>italic content</i>
 </p>

然后当文档加载进程时

 $(function(){
    var text = $("#sample-code").text();
    // should probably ensure the length is greater than 80 chars
    var sample = text.substr(0, 80);
    var runoff = text.substr(81);

    $("#sample-code").text(sample);
    $("#run-off").text(runoff);
 });

JsFiddle

答案 2 :(得分:0)

如果你只是想看看,试试span#sample-code {max-width:看起来不错的px; }