简体   繁体   中英

How to detect a class and get li number using jQuery?

I am trying to get li number by detect a class.

Example :

    <ul>
    <li></li>
    <li></li>
    <li class="current"></li>
    <li></li>
    <li></li>
    </ul>
<div class="value"></div>

I want the class="current" <li> number.

$('.value').text(//need class="current" li number);

我认为 index() 是你要找的

$('.current').index()

Your question is not entirely clear so I'm not 100% sure what you're looking for the "index" or the "actual text".

For learning purposes, here are the steps:
1) use a .<classname> to specify the class you want to look for
2) use index() or html() or text() to get the info you need

Additional info/explanation of each usage can be found here:

https://api.jquery.com/index/
$('.current').index()

http://api.jquery.com/html/
$('.current').html()

http://api.jquery.com/text/
$('.current').text()

Based on your update, it seems like you want the index, correct? This is how you would accomplish this:

$('.value').text($("li.current").index()); //2

Here class is find by getting children of ul and finding whether element has class or not. If class is available then print class name and element value

.attr('class') return class name if available else return undefined

 $('ul').children().each(function(index, el) { if ($(this).attr('class')) { alert($(this).attr('class')); alert($(this).text()); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li class="current">3</li> <li>4</li> <li>5</li> </ul>

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