Javascript jQuery indexOf 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10406300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery indexOf function?
提问by qwertymk
I'm trying to get a location of an element in a jQuery set.
我正在尝试获取 jQuery 集中元素的位置。
I want to be able to do something like this:
我希望能够做这样的事情:
$('ul').find('a').indexOf('.active');
And get the location of the .active
in the set of a
's.
并获取's.active
集合中的位置a
。
Is there something like an indexOf()
function for jQuery? The index()
method doesn't work
有没有类似indexOf()
jQuery的函数?该index()
方法不起作用
回答by tobyodavies
if you pass a jQuery set ($searchFor
) as an argument to the index
method of another jQuery set ($searchIn
) i.e.
如果你将一个 jQuery set ( $searchFor
) 作为参数传递给index
另一个 jQuery set ( $searchIn
)的方法,即
$searchIn.index($searchFor)
it will return the index of $searchFor
in the set $searchIn
它将返回$searchFor
集合中的索引$searchIn
In your example:
在你的例子中:
$('ul a').index($('ul a.active'));
?
?
回答by gdoron is supporting Monica
You just need to give the index
function a jQuery object:
你只需要给index
函数一个 jQuery 对象:
var elements = $('ul a');
var index = elements.index(elements.filter('.active')); // 2
alert(index);
现场演示?
There is no such function out of the box, it can be done easily like this:
开箱即用没有这样的功能,可以像这样轻松完成:
var index = -1;
$('ul a').each(function(i){
if ($(this).hasClass('active')){
index = i;
return false;
}
});
alert(index);
回答by rkw
Your logic is sound, you're just grabbing the wrong element: http://jsfiddle.net/xz9dW/19/
你的逻辑是合理的,你只是抓住了错误的元素:http: //jsfiddle.net/xz9dW/19/
var index = $('ul a.active').closest('li').index();
The a
link has no index()
value since it has no siblings; you have to grab the li
该a
链接没有任何index()
价值,因为它没有兄弟姐妹;你必须抓住li
回答by Control Freak
You can do this by just asking for it in the selector:
你可以通过在选择器中要求它来做到这一点:
$('ul a.active')
What do you mean by getting the location however? Do you mean position? or URL?
但是,获取位置是什么意思?你是说位置吗?或网址?
If you would like to know which one you click
on lets say.. You would use $(this)
inside your event function. Here is an example which returns the current position of the element you click on, if there are multiple with the .active
class:
如果您想知道click
您使用的是哪一个,可以说.. 您将$(this)
在事件函数中使用。这是一个示例,它返回您单击的元素的当前位置,如果类中有多个元素.active
:
To get the position:
要获得职位:
$('ul a.active').click(function(){
alert( $(this).position() );
})
To get the URL location:
要获取 URL 位置:
$('ul a.active').click(function(){
alert( $(this).attr('href') );
})