JQuery Unique()函数无法正常工作 [英] JQuery Unique() function not working properly

查看:146
本文介绍了JQuery Unique()函数无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个允许用户选择多个卡片的界面。每张卡都有一个数据名称属性,也可能有相应的菜单项。如果他们在主视图中选择卡片,它也会突出显示菜单项目。点击某些内容后,我将selected类添加到其中。然后我获取所有已选择项目并计算唯一数据名称属性以获取所选实际项目的数量。

I'm working on an interface that allows the user to select multiple "cards". Each card has a "data-name" attribute and may also have a corresponding menu item. If they select the card in the main view, it also highlights the menu item. When something is clicked, I add the "selected" class to it. I then get all the 'selected' items and count the unique data-name attributes to get the number of actual items selected.

选择最多5个时这非常有效项目。出于某种原因,在第6项上,unique()函数似乎停止正常工作。我无法用jsfiddle复制这个问题,但代码有点复杂,因为本地我也处理类型,但我认为这与问题无关。

This works very well when selecting up to 5 items. For some reason, on the 6th item the unique() function seems to stop working correctly. I was unable to duplicate this issue with jsfiddle, but the code was a bit less complex, as locally I'm also dealing with "types", but I think that's irrelevant to the problem.

以下是我选择第5项后相关数组的一些截图。

So here are some screenshots of the relevant arrays after I have selected the 5th item.

在这里您可以看到所有选定的项目。正如预期的那样有10个。这个断点就在unique()调用之前。

Here you see ALL selected items. There are 10, as expected. This breakpoint is just before the unique() call.

在这里您可以看到唯一的选定项目。正如预期的那样,有5个。

然后我选择第6个...... 12,正如所料......

And then I select the 6th one... 12, as expected...

<强> Aaand现在我们有一个神秘的复制品!为什么???

Aaand now we have a mysterious duplicate! Why???

这个一贯地发生;每一次。请注意我选择的项目无关紧要。我添加了多达10个虚拟物品,它总是第6个被弄糊涂了。

This happens consistently; every single time. And note that it doesn't matter which item I select last. I've added as many as 10 dummy items and it's always the 6th one that it gets confused on.

推荐答案

取自< a href =http://api.jquery.com/jQuery.unique/ =noreferrer> jQuery.unique():


描述:在适当的位置对DOM元素数组进行排序,并删除重复项。请注意,这仅适用于DOM元素的数组,而不适用于字符串或数字。

Description: Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

如果要获取唯一的字符串数组或数字,你需要使用自己的功能。这是从以前回答的与您类似的问题中取得的一个:

If you want to get a unique array of string or numbers, you will need to use your own function. Here's one taken from a previously answered question similar to yours:

function unique(array) {
    return $.grep(array, function(el, index) {
        return index == $.inArray(el, array);
    });
}

这篇关于JQuery Unique()函数无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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