开发者

jQuery replace hyphens with spans for blogger date header

I'm looking to customize the default date header in blogger with jQuery.

The original output is:

<h2 class='date-header'>201开发者_C百科1-01-20</h2>

I want to wrap the YYYY, MM, and DD in spans so I can manipulate them as child nodes.

The result would be:

<h2 class='date-header'><span class="dhy">2011</span><span class="dhm">01</span><span class="dhd">20</span></h2>

Each attempt of mine adds extra tags so it's a nested mess.

Anybody have a good solution?


Here's a nice functional solution:

$('.date-header').html(function() {
    var txt = $(this).text();
    var classes = ['dhy', 'dhm', 'dhd'];
    $(this).html($.map(txt.split(/-/), function(val) {
        return $('<span/>', {'class': classes.shift()}).text(val)[0];
    }));
});

http://jsfiddle.net/ThiefMaster/WdRAw/


If it always has the same format of YYYY-MM-DD then you could use split to get the elements, loop through them, create your output HTML then add that as the HTML of the h2.

$(function()
{

   $(".date-header").each(function()
   {

      var arrDate = $(this).text().split("-");

      var strOut = '<span class="dhy">'+arrDate[0]+'</span>-';
      strOut+= '<span class="dhm">'+arrDate[1]+'</span>-';
      strOut+= '<span class="dhd">'+arrDate[2]+'</span>';

      $(this).html(strOut);

   });

});

And a fiddle: http://jsfiddle.net/ahallicks/xGa2J/2/


I think this should do it:

var header = $('.date-header');
var d = header.text().split('-');
header.html('<span class="dhy">' + d[0] + '</span><span class="dhm">' + d[1] + '</span><span class="dhd">' + d[2] + '</span>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜