Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - 在jquery或javascript中的特定类之前计数元素(Count elements before a specific class in jquery or javascript)

I have to count all classes with the name " loader " before the class " p16 " (for example).(我必须在类“ p16之前计算所有名称为“ loader ”的类。)

In this case the right answer would be: 4(在这种情况下,正确的答案是: 4) <div class="loader p12"></div> <div class="loader p13"></div> <div class="loader p14"></div> <div class="loader p15"></div> <div class="loader p16"></div> <div class="loader p17"></div> <div class="loader p18"></div> I tried serveral solutions:(我尝试了服务器解决方案:) var $slides = $('.loader'); var $current = $slides.find('.p5'); var index = $slides.index($current) + 1; var total = $slides.length; var n = $('.loader').index('.p5'); alert(n); alert(index); Here is a fiddle:(这是一个小提琴:) https://jsfiddle.net/mc184j7f/(https://jsfiddle.net/mc184j7f/) Thank you very much.(非常感谢你。)   ask by Lars Vegas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use prevAll()(您可以使用prevAll())

console.log($('.p16').prevAll('.loader').length) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="loader p12"></div> <div class="loader p13"></div> <div class="loader p14"></div> <div class="loader p15"></div> <div class="loader p16"></div> <div class="loader p17"></div> <div class="loader p18"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...