开发者

Problem with adding class to every children node

I have problem with adding class to every list element. 开发者_如何学GoThis is example html:

<ul id="main_list">
    <li>item1</li>
    <li>item2<li>
<ul>

And my jquery code which i don't understand why it don't work like i expect:

   $(function(){
        $('#main_list').children().each(function(){
            $(this).addClass(function(){
                return $(this).index()})
            })
          })


It's because the jQuery object on which you're calling addClass has only one item in it (you're creating that jQuery object via $(this)). Try this:

$("#main_list > li").addClass(function() {
    return $(this).index();
});

...if you're really trying to assign classes like 0, 1, etc. I think I'd probably put something in front of those numbers, though; I can't immediately find it in the spec, but I don't think class names can start with digits. So:

$("#main_list > li").addClass(function() {
    return 'n' + $(this).index();
});

...for n0, n1, etc.


To make valid class names (which can't start with a digit):

$("#main_list li").addClass(function() {
    return("myItem" + $(this).index());
});

But, it sounds to me like you might rather be setting an id:

$("#main_list li").attr("id" function() {
    return("myItem" + $(this).index());
});

Looking at Cris' (the original poster) comments to other answers, it sounds like what you want to do is to be able to extract the ordered position from the object at some later date. It might be easier to just put a data attribute on the object that represents it's order like this:

// put an attribute on each object that represents it's index so that's easier to get later
$("#main_list li").each(function(index){
    $(this).data("pos", index);
});

Then later, you can access that data value with this:

item.data("pos");

This seems a lot cleaner to me than parsing a number out of class name that you have no other use for.

Example here: http://jsfiddle.net/jfriend00/RDvw2/.


I assume you are trying to number the li's based on their position in the ul?

function addClasses( )
{
    $( '#main_list' ).children( ).each( function( index )
    {
        $( this ).addClass( 'myClass' + index );
    } );
}

edit: as jfriend00 pointed out, class name can not start with a digit.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜