简体   繁体   中英

I have n list items. I need to get no of item which has class active

I am working on a slider which changes the active class on click of next and previous, I want the nth child each time which has class active. eg in current scenario it should return 3

HTML

<div class="my-list">
    <ul>
        <li><a href="#"> list item</a></li>
        <li><a href="#"> list item</a></li>
        <li class="active"><a href="#"> list item</a></li>
        <li><a href="#"> list item</a></li>
        <li><a href="#"> list item</a></li>
        <li><a href="#"> list item</a></li>
        <li><a href="#"> list item</a></li>
    </ul>
</div>

JavaScript

function getCurrentItem() {
    var listItem = $(".my-list ul li");
    var items = [];
    for (i = 0; i < listItem.length; i++) {
        items[i] = listItem;
        if($(items[i]).hasClass("active")){
            console.log("here: "+i);
        }
    }
}
 getCurrentItem();

index() can be used to the the index of the element. Note that index() will return zero-based index of the element. So, in current example, it'll return 2.

return $('.my-list li.active').index();

If the index need to be start from 1, add one to the zero-based index.

return $('.my-list li.active').index() + 1;

 console.log($('.my-list li.active').index() + 1); 
 .active { color: green; font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my-list"> <ul> <li><a href="#"> list item 1 </a></li> <li><a href="#"> list item 2</a></li> <li class="active"><a href="#"> list item 3</a></li> <li><a href="#"> list item 4</a></li> <li><a href="#"> list item 5</a></li> <li><a href="#"> list item 6</a></li> <li><a href="#"> list item 7</a></li> </ul> </div> 

您可以使用index()来做到这一点:

var currentActive = $('li.active').index() + 1; // 3, in this case
function getCurrentItem() {
    var listItem = $(".my-list ul li");
    for (i = 0; i < listItem.length; i++) {
        if ($(listItem[i]).hasClass("active")) {
            console.log("here: " + i);
            return i + 1; //weve found it, lets return
            break;
        }
    }
    return " empty";
}
alert(getCurrentItem()); //should alert 3 in your case

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