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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:11:15  来源:igfitidea点击:

jQuery indexOf function?

javascriptjquery

提问by qwertymk

I'm trying to get a location of an element in a jQuery set.

我正在尝试获取 jQuery 集中元素的位置。

Here's what I tried so far.

这是我到目前为止所尝试的。

I want to be able to do something like this:

我希望能够做这样的事情:

$('ul').find('a').indexOf('.active');

And get the location of the .activein 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 indexmethod of another jQuery set ($searchIn) i.e.

如果你将一个 jQuery set ( $searchFor) 作为参数传递给index另一个 jQuery set ( $searchIn)的方法,即

$searchIn.index($searchFor)

it will return the index of $searchForin 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 indexfunction a jQuery object:

你只需要给index函数一个 jQuery 对象:

var elements = $('ul a'); 
var index = elements.index(elements.filter('.active')); // 2

alert(index);

Live DEMO?

现场演示



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);

Live DEMO

现场演示

回答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 alink 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 clickon 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 .activeclass:

如果您想知道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') );
 })