Javascript 如何在 jQuery 数组中找到 indexOf 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7768333/
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 03:32:30  来源:igfitidea点击:

How to find indexOf element in jQuery array?

javascriptjqueryarraysindexof

提问by IAdapter

I have two selectors

我有两个选择器

    var allNodes = $("a.historyEntry");
    var errorNodes = $("a.historyEntry.error");

I would like to to find a node before first error node, so I need to find an index of first error node, how to do it?

我想在第一个错误节点之前找到一个节点,所以我需要找到第一个错误节点的索引,怎么做?

I tried to use inArray method, but it doesn't work for this

我尝试使用 inArray 方法,但它不适用于此

$.inArray(allNodes, errorNodes.first())

or

或者

$.inArray(allNodes, $(errorNodes.first()))

Is there any fast way to do it in jQuery or do I have to use for loop?

有没有什么快速的方法可以在 jQuery 中做到这一点,还是我必须使用 for 循环?

回答by Matt

index()?

index()?

It's like indexOf... but just without the Of... it returns the index of the element if it exists, and -1 if it doesn't.

这就像indexOf... 但只是没有Of... 它返回元素的索引(如果存在),如果不存在则返回 -1。

回答by fireshadow52

Use index(). It does exactly the same thing as indexOfin java.

使用index(). 它的作用与indexOf在 java中完全相同。

回答by Joe

$.inArrayvalue is the first parameter then the array:

$.inArray值是第一个参数,然后是数组:

$.inArray(allNodes, errorNodes.first())

should be:

应该:

$.inArray(errorNodes.first(), allNodes)

Example

例子