获取具有某个类的元素的内容和Href

时间:2012-02-22 06:46:19

标签: javascript jquery

有一个Div有9个Spans作为其成员。其中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/

如何像上面那样格式化无序列表?

1 个答案:

答案 0 :(得分: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