简体   繁体   中英

is there any easier way to get the LI list number in one UL?

i have following html code:

<ul>
    <li>Text</li>  <!-- number:0; means first one-->
    <li>Text</li>  <!-- number:1; second one-->
    <li>Text</li>  <!-- number:2; third one-->
    <li>Text</li>  <!-- number:3 -->
    <li>Text</li>  <!-- number:4 -->
    <li>Text</li>  <!-- number:5 -->
</ul>

in my method, set a attribute number to every li

i = 0;
$('li').each(function()
    {
        $(this).attr('number',i);
        i++;
    });

using $(this).attr('number') to get its number;

here is jsFiddle DEMO http://jsfiddle.net/8tpab84s/ , is working

but i think the method is complicated, if the DOM li be changed, i need to set the number attribute again.

is there a easier way to instead this method ? without set any attribute.

thanks for your response.

You can use attr() with a function as the second argument:

$('li').attr('number', function(_index) {
    return _index;
});

Demo: http://jsfiddle.net/techfoobar/8tpab84s/4/

Thanks to user: NicoSantangelo - You can simply use the first argument of the callback function instead of $(this).index()

DEMO

 var i = 0;
    $('li').each(function(i)
        {
           alert(i);
        });

you can use if statement after that

      var i = 0;
        $('li').each(function(i)
            {
               if(i == 1){ // that mean the li number 2
                 // your code here
               }
            });

and to get number of all li just use

$('li').length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM