获得具有某一类

问题描述:

有9个跨度为成员一个div元素的含量和HREF。其中3人拥有“aaa”级,3人拥有“bbb”级,3人拥有“ccc”级。格式为:获得具有某一类

<span class="aaa">aaa</span> 
    <span class="bbb"><strong>bbb</strong></span> 
    <span class="ccc"><a href="0.html">ccc</a></span> 

    <span class="aaa">aaa1</span> 
    <span class="bbb"><strong>bbb1</strong></span> 
    <span class="ccc"><a href="1.html">ccc1</a></span> 

    <span class="aaa">aaa2</span> 
    <span class="bbb"><strong>bbb2</strong></span> 
    <span class="ccc"><a href="2.html">ccc2</a></span> 

还有一个无序列表。

我想要的是来填充列表项无序列表。无序列表的新的格式应该是这样的:

<ul class="container"> 
    <li> 
     <a href="0.html"> 
      aaabbb 
     </a> 
    </li> 

    <li> 
     <a href="1.html"> 
      aaa1bbb1 
     </a> 
    </li> 

    <li> 
     <a href="2.html"> 
      aaa2bbb2 
     </a> 
    </li> 
</ul> 

我的代码是下面,但它不工作:

http://jsfiddle.net/Tgser/

我如何可以格式化无序列表像上面?

+0

守则红色的jsfiddle告诉你,什么是错的......而且,你有HTML,JS和CSS的部分,您不需要添加文档类型等。此外,你不包括在“jQuery库框架“ – elclanrs 2012-02-22 06:53:17

+0

是的,我知道。也许是因为我在HTML部分中混合了HTML和Javacript。如果你将它复制到Notepad ++中,它会很好... – Bayu 2012-02-22 06:55:38

+0

我包含了jQuery库。请将整个代码复制到您的Web开发IDE中... – Bayu 2012-02-22 06:57:47

$(function() 
{ 
    //you can use `.filter()` to filter a list down to the elements you want, hasClass() returns true/false, not a set of elements 
    var allLatestNews = $('.source').children(), 
     span_aaa = allLatestNews.filter('.aaa'), 
     span_bbb = allLatestNews.filter('.bbb'), 
     span_ccc = allLatestNews.filter('.ccc'), 
     output = [];//this is used to add HTML to the DOM 

    //you only need to loop the number of elements in each `span_***` variable, not the total number of span elements 
    for(var i = 0; i < span_aaa.length; i++) 
    { 
     //instead of manipulating the DOM every iteration of the loop, we add the string of HTML to an array 
     output.push('<li><a href="' + span_ccc.eq(i).children().attr("href") + '">' + span_aaa.eq(i).text()+ span_bbb.eq(i).text() + span_ccc.eq(i).text() + '</a></li>'); 
    } 

    //then we append all the HTML at once 
    $('.container').append(output.join('')); 
});​ 

这里是一个演示:http://jsfiddle.net/Tgser/5/

通知使用.text()得到<span>元素的文本和使用.eq(i)以选择对应的索引(i)jQuery对象,而不是使用[i],其选择相应的DOMElement

+0

非常感谢!这非常复杂 – Bayu 2012-02-22 07:07:38

+0

感谢您的进一步解释。我从来不知道.eq(i)和[i]之间的区别。 – Bayu 2012-02-22 07:14:35