有一个 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>
我的代码如下,但它不起作用:
如何像上面那样格式化无序列表?
最佳答案
$(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/