简体   繁体   中英

jquery wrap elements with div

Gurus,

I have this.

<td style="width:100px">
Queued:465
Rejects:3897
Offers:31
</td>

and need to make it as

<td style="width:100px">
<span class="label">Queued:</span><span class="data">465</span> <br>
<span class="label">Rejects:</span><span class="data">3897</span><br>
<span class="label">Offers:</span><span class="data">31</span>
</td>

Instead of one single line (Queued:465 Rejects:3897 Offers:31), I want to give a break after the numbers(they are dynamic). Queued, Rejects, Offers are fixed.

This is what I tried with.

$('td:contains(Queued:)').html(function() {
    return $(this).html().replace('Queued:', '<span class="label">Queued: </span>');
});
$('td:contains(Rejects:)').html(function() {
    return $(this).html().replace('Rejects:', '<br><span class="label">Rejects: </span>');
});
$('td:contains(Offers:)').html(function() {
    return $(this).html().replace('Offers:', '<br><span class="label">Offers: </span>');
});
$("td").html(function(i, val) {
    return $.trim(
        val.replace(/[a-z]+/ig, '<span class="label">$&</span>')
           .replace(/\d+/g, '<span class="data">$&</span>')
    ).replace(/\n/g, "<br />");
});

DEMO: http://jsfiddle.net/dfRzY/

You can also go down the .split route rather than the Regex route.

var $td = $("td"),
    rows = $td.html().trim().split("\n"),
    html = [];

for (var x=0; x<rows.length; x++){
  var line = rows[x].split(":");

  html.push(
    "<span class='label'>"+line[0]+":</span>"+
    "<span class='data'>"+line[1]+"</span>"
  );
}
$td.html(html.join("<br>"));

Edit: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM