开发者

how to add the three beginning a unique class?

开发者 https://www.devze.com 2023-03-22 10:38 出处:网络
<ul class=\"topunm\"> <li><a href=\"#\">test</a></li> <li><a href=\"#\">test</a></li>
<ul class="topunm">
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
</ul>

i want to add the number before the li. the following is my code:

$(开发者_StackOverflow"ul.code-topnumb > li").each(function() {
    $(this).prepend('<span class="num">' + ($(this).index() +1) + "</span>");
})

but now, i want to add a background to only the first three number. how to change the code? thank you.


I think you want to do something like this. You might want to change prepend to before though if you want your span to be outside the li tag. But I don't think it's valid to have a <span> directly in a <ul>

$("ul.topnum > li").each(function(i, el) {
    if(i < 3)
        $(el).css('background-color', '#0FF');
    $(el).prepend('<span class="num">' + (i+1) + "</span>");
})


Something like this?

$("ul.code-topnumb > li").each(function() {
    var cl;

    if($(this).index() < 3){
        cl = "num bgnd";
    }else{
        cl = "num";
    }

    $(this).prepend('<span class="' + cl + '">' + ($(this).index() +1) + "</span>");
})


Use slice:

$(function(){
    $("ul.code-topnumb > li").slice(0, 3).each(function() {
        $(this).prepend('<span class="num">' + ($(this).index() +1) + "</span>");
    });
});


How about this?

$("ul.code-topnumb > li").each(function() {
    $(this).prepend('<span class="num">' + ($(this).index() +1) + "</span>");
});

$('.num').slice(0,3).css('background-color', 'red');
0

精彩评论

暂无评论...
验证码 换一张
取 消