是否可以将唯一的CSS类附加到多个<li>元素,或者使用Jquery对它们进行重新排序?</li>

时间:2011-08-22 17:24:14

标签: javascript jquery css squarespace

目前正在Squarespace.com平台上工作,我想重新排序一个默认为按字母排序的动态博客类别索引。这就是Squarespace生成代码的方式:

<div id="moduleContentWrapper11663355" class="widget-wrapper widget-type-journalarchive">
    <div id="moduleContent11663355">
        <ul class="archive-item-list-pt">
            <li>
            <a href="/blog/category/category-one">Category One</a>
            <span class="entry-count">(1)</span>
            </li>
            <li>
            <a href="/blog/category/category-two">Category Two</a>
            <span class="entry-count">(1)</span>
            </li>
            <li>
            <a href="/blog/category/category-three">Category Three</a>
            <span class="entry-count">(1)</span>
            </li>
        </ul>
    </div>
</div>

是否可以使用Jquery重新排序条目,或者更糟糕的是,我可以为每个<li>附加一个唯一的CSS类,以便我可以使用CSS操作每个类吗?

谢谢!

5 个答案:

答案 0 :(得分:4)

dom实际上只是一个复杂的集合......你可以使用jquery对li进行排序,就像数组一样。

var mylist = $('#moduleContent11663355 > ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

感谢http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

答案 1 :(得分:3)

var i = 1;
$('.archive-item-list-pt li').each(function(item) {
   $(item).addClass('myClass'+i);
});

答案 2 :(得分:2)

$('.archive-item-list-pt li').each(function(i,j) {
   $(this).addClass('yourClass'+i);
});

这里是小提琴http://jsfiddle.net/h2gfT/7/

<强>更新

$('.archive-item-list-pt li').each(function(i,j) {
   var cls=$(this).children("a").text().toLowerCase();
    var idx = cls.replace(' ','-');

    $(this).addClass(idx);
});

这里是小提琴http://jsfiddle.net/h2gfT/9/

一个用jquery chaining hotness

$('.archive-item-list-pt li').each(function(i,j) {
   var cls=$(this).children("a").text().toLowerCase().replace(' ','-');  
   $(this).addClass(cls);
});

http://jsfiddle.net/h2gfT/11/

答案 3 :(得分:0)

根据任意键功能

对项目进行排序

http://blog.mirotin.net/125/jquery-sortitems

答案 4 :(得分:-1)

使用jQuery对条目进行排序可以通过几种不同的方式进行,但如果您只是想为每个方法添加CSS,则可以通过两种不同的方式进行。

$('li').each(function(l) { $(this).attr('class', '<insertnameofcssclasshere>') })

$('li').each(function(l) { $(this).css(<insertcssstuff here>) })

当然,这些会将它应用于您网页上的所有li元素。如果您想要影响其中一些选择器,您可能希望使用更具体或包含的选择器。