javascript - 获取具有特定类的元素的内容和 Href

标签 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/

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

最佳答案

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

关于javascript - 获取具有特定类的元素的内容和 Href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9390287/

相关文章:

javascript - 单击时如何在可折叠 div 上同时扩展宽度和高度?

javascript - 将所有代码放在 `$(document).ready` 中是否安全?

javascript - JS函数获取元素的第n个字符的滚动量

javascript - jQuery 选择具有特定属性的第一个 child

jquery - 带过渡动画的粘性标题

javascript - 使用 jQuery 替换和正则表达式替换字符串

javascript - 以创建者用户身份单击按钮时运行函数 - Google 电子表格

javascript - 使用ajax加载Javascript时出错

javascript - CSS 显示属性已设置但在代码运行时不可见

javascript - RelaodGrid 操作时 jqGrid PostData 中的 DateTime