如何检查是否jQuery对象数组中存在吗? [英] How to check if jQuery object exist in array?

查看:317
本文介绍了如何检查是否jQuery对象数组中存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个项目阵列,我想知道,如果项目存在阵列

项目是一个jQuery对象,例如 $(C)。你可以假设 item.length == 1

阵列是jQuery的对象,例如数组 [$(A),$(B)。此阵列中的每个项可以重新present 0,1,或更多的对象。

下面是我认为实现这个:( rel=\"nofollow\">现场演示)

 函数inArray(项目,编曲){
    对于(VAR I = 0; I< arr.length;我++){
        VAR项目= $ .makeArray(ARR [I]);        对于(VAR K = 0; K< items.length; k ++){
            如果(项目[K] ==项目[0]){
                返回true;
            }
        }
    }    返回false;
}

你能找到一个更优雅的实现?


示例:

HTML

 < D​​IV CLASS =一个>您好< / DIV>
< D​​IV CLASS =一个>堆叠式和LT; / DIV>
< D​​IV CLASS =一个>&溢出LT; / DIV>< D​​IV CLASS =B>都具有< / DIV>
< D​​IV CLASS =B>将< / DIV>
< D​​IV CLASS =B>好的和LT; / DIV>
< D​​IV CLASS =B>日间及LT;!/ DIV>< D​​IV CLASS =C>再见< / DIV>

JS:

 的console.log(inArray($(。一个)。当量(2),[$(。一个),$(。B)])) ; //真
的console.log(B。inArray($()当量(3),[$(一),$(B)])); //真
的console.log(inArray($(C),[$(A),$(B))); //假
的console.log(inArray($()当量(2),[$(B)])一。); //假
的console.log(inArray($()当量(2),[])一。); //假
的console.log(inArray($(C),[$(格))); //真


据Felix的建议:

[$(selector1),$(selector2),...] 可以简化为

  $(selector1,selector2,...)

  $(selector1)。新增(selector2)...

和然后它可以被实施为:

 函数inArray(项目,编曲){
  回报(arr.index(项目)!= -1);
}

这里现场演示

Given an item and an array, I would like to know if item exist in array.

item is a jQuery object, e.g. $(".c"). You can assume that item.length == 1.

array is an array of jQuery objects, e.g. [$(".a"), $(".b")]. Each item in this array may represent 0, 1, or more objects.

Here is how I thought to implement this: (live demo here)

function inArray(item, arr) {
    for (var i = 0; i < arr.length; i++) {
        var items = $.makeArray(arr[i]);

        for (var k = 0; k < items.length; k++) {
            if (items[k] == item[0]) {
                return true;
            }
        }
    }

    return false;
}

Can you find a more elegant implementation?


Example:

HTML:

<div class="a">Hello</div>
<div class="a">Stack</div>
<div class="a">Overflow</div>

<div class="b">Have</div>
<div class="b">a</div>
<div class="b">nice</div>
<div class="b">day!</div>

<div class="c">Bye bye</div>

JS:

console.log(inArray($(".a").eq(2), [$(".a"), $(".b")])); // true
console.log(inArray($(".b").eq(3), [$(".a"), $(".b")])); // true
console.log(inArray($(".c"), [$(".a"), $(".b")]));       // false
console.log(inArray($(".a").eq(2), [$(".b")]));          // false
console.log(inArray($(".a").eq(2), []));                 // false
console.log(inArray($(".c"), [$("div")]));               // true

解决方案

According to Felix's suggestion:

[$(selector1), $(selector2), ... ] can be simplified to

$(selector1, selector2, ...)

or

$(selector1).add(selector2)...

and then it can be implemented as:

function inArray(item, arr) {
  return (arr.index(item) != -1);
}

Live demo here

这篇关于如何检查是否jQuery对象数组中存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆