2012-02-22 62 views
0

有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

回答

3
$(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

相關問題