使用jQuery包装html的某些部分

Wrapping some part of html using jQuery

本文关键字:些部 html jQuery 包装 使用      更新时间:2023-09-26

我写的是:

<div class="the_notice">
    <span class="time"> | 3:48pm</span>
    To <strong>2013-03-16_10-56-33</strong> By <strong>XYX</strong>
</div>

在结果中,我想要这样的:

<div class="the_notice">
    <span class="time"> | 3:48pm</span>
    <div class="wrap">
      To <strong>2013-03-16_10-56-33</strong> By <strong>XYX</strong>
    </div>
</div>

如何使用jQuery实现这一点?

如果内容总是相同的,你可以这样做

$('.the_notice').contents().slice(2).wrapAll('<div class="wrap"/>');
http://jsfiddle.net/Ysq48/

Demo

   var temp = $('.time');
   $('.time').remove();
   $(".the_notice").contents().wrapAll('<div class="wrap" />');
   $(".the_notice").prepend(temp);

阅读这个链接,它可能会对你有所帮助:使用jquery创建html元素的最有效方法是什么

我的答案是这样的:

var myTimeIsHere = //calculate your time here;
var x = //calculate x here.;
var y = //calculate y here.;
var newHTML = "<span class='time'>" |+ myTimeIsHere+"</span>"+
              "<div class='wrap'>To <strong> "+x+" </strong>"+
              "by "+y+"</div>";
$(".the_notice").html(newHTML);

一行(或三行):

$('.the_notice')
     .wrapInner($('<div class="wrap">'))
     .prepend($('.the_notice .time').detach());

JSFIDDLE