使用jQuery操作HTML

时间:2010-10-24 18:05:46

标签: jquery

我正在尝试设置一些从Google Calendar生成的HTML样式,这是我无法控制的。这很简单的HTML。

这就是我所拥有的:

    <li><a><span class="data">When: gio 27 gen 2011<br /><br />Where: XXXX<br />Event state: confirmed</span></a></li>
<li><a><span class="data">When: gio 20 gen 2011<br /><br />Where: XXXX<br />Event state: confirmed</span></a></li> 

这就是我想要的:

<li>
    <a>
        <span class="when">When:</span>
        <span class="day">gio</span>
        <span class="number">27</span>
        <span class="month">gen</span>
    </a>    
</li>
<li>
    <a>
        <span class="when">When:</span>
        <span class="day">gio</span>
        <span class="number">20</span>
        <span class="month">gen</span>
    </a>    
</li>

这个混乱的代码:

$(function(){
    var words = $('div.data').text().split(" ");    
    $("div.data").html("<span>" + words + "</span>");
    $("div.data span:first").addClass("when");  
});

这就是我得到的:

   <li>
    <a title="" class="tip">
        <div class="data">
            <span class="when">
                <a xmlns="http://www.w3.org/1999/xhtml">when:,gio,27,gen,2011
where:,XXX,XXX
Event,state:,confirmedWhen:,gio,20,gen,2011
where:,XXX,XXX
Event,sate:,confirmed
                </a>
            </span>
        </div>
    </a>    
</li>

如你所见,我有这个新的&lt; a&gt;元素(为什么?)和两者&lt; li&gt;文本在同一&lt; span&gt;内。两次(说实话,第二次没有“什么时候”课)。这应该不难做到。这对我来说太难了。

2 个答案:

答案 0 :(得分:1)

$(function(){
    var words = $('div.data').text().split(" ");    
    $("div.data").html("<span class='when'>" + words[0] + "</span>");
    $("div.data").append("<span class='day'>" + words[1] + "</span>");
    //...etc
});

答案 1 :(得分:0)

你可以试试这个:

$('span.data').each(function() {
  var text = $(this).text();
  text = text.substr(0, text.indexOf("Where")); //remove stuff from "Where:"
  var words = text.split(" ");
  var parent = $(this).parent();
  $(this).remove();
  var classes = ["when", "day", "number", "month", "year"];
  for (var i = 0; i < words.length; i++) {
    parent.append($("<span />").addClass(classes[i]).text(words[i]));
  }
});