[英]A one-liner for finding the index of an element that has certain class within a jQuery set of elements?
I've got an arbitrary structure like this: 我有一个像这样的任意结构:
<h2>Foo</h2>
<p>Foo foo</p>
<p>Foofoo</p>
<h2>Bar</h2>
<h2 class=highlighted>Baz</h2>
<p>Baz</p>
<h2>Quux</h2>
<p>Quux quux</p>
In my JS i already have all h2 elements in a jQuery object: 在我的JS中,我已经在jQuery对象中包含了所有h2元素:
var $headings = $('h2');
Now i need to find which of those headings has the highlighted class. 现在,我需要找到那些突出显示类的标题。
So for the above structure the third heading is highlighted, so i expect to receive the answer 2 (JS counts from zero). 因此,对于上述结构,第三个标题将突出显示,因此我希望收到答案2(JS计数从零开始)。
I've managed to solve this task with: 我设法用以下方法解决了这个任务:
function foo($jQueryObject) {
var number;
$jQueryObject.each( function(index, element) {
if ($(element).hasClass('highlighted')) {
number = index;
return false;
}
});
return number;
}
Demo: http://jsbin.com/acaGeJi/1/ 演示: http : //jsbin.com/acaGeJi/1/
But i'm sure there's a more elegant way, something like $headings.index('.highlighted');
但是我敢肯定还有一种更优雅的方法,比如$headings.index('.highlighted');
. 。 Can you please suggest it? 你能建议一下吗?
You can use the map
method to get the index: 您可以使用map
方法获取索引:
var index = $jQueryObject.map(function(i, e){
return e.hasClass('highlighted') ? i : null;
})[0];
You can also use the index
method, but then you have to get the element to look for first, so that means that you look for it twice: 您还可以使用index
方法,但是随后必须先获取要查找的元素,这意味着您需要对其进行两次查找:
var index = $jQueryObject.index($jQueryObject.filter('.highlighted'));
You can use the $.index
function 您可以使用$.index
函数
var search = $( ".highlighted" );
alert( "Index: " + $( "h2" ).index( search ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.