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.
我正在开发一个允许用户选择多个“卡片”的界面。每张卡都有一个“数据名称”属性,也可能有相应的菜单项。如果他们在主视图中选择了卡片,它也会突出显示菜单项。点击某些内容后,我会将“selected”类添加到其中。然后,我获取所有“选定”项目并计算唯一数据名称属性以获取所选实际项目的数量。
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个项目时,这非常有效。由于某种原因,在第6项上,unique()函数似乎停止正常工作。我无法用jsfiddle复制这个问题,但代码有点复杂,因为本地我也在处理“类型”,但我认为这与问题无关。
So here are some screenshots of the relevant arrays after I have selected the 5th item.
所以这里是我选择第5项后相关数组的一些截图。
Here you see ALL selected items. There are 10, as expected. This breakpoint is just before the unique() call.
在这里您可以看到所有选定的项正如预期的那样,有10个。此断点就在unique()调用之前。
Here you see unique selected items. There are 5, as expected.
在这里您可以看到唯一的选定项正如预期的那样,有5个。
And then I select the 6th one... 12, as expected...
然后我选择第6个... 12,正如预期的那样......
Aaand now we have a mysterious duplicate! Why???
Aaand现在我们有一个神秘的复制品!为什么???
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.
这种情况始终如一每一次。请注意,我最后选择的项目并不重要。我添加了多达10个虚拟物品,它总是第6个被弄糊涂了。
1 个解决方案
#1
18
Taken from jQuery.unique():
取自jQuery.unique():
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.
描述:对一组DOM元素进行排序,删除重复项。请注意,这仅适用于DOM元素的数组,而不适用于字符串或数字。
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);
});
}
#1
18
Taken from jQuery.unique():
取自jQuery.unique():
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.
描述:对一组DOM元素进行排序,删除重复项。请注意,这仅适用于DOM元素的数组,而不适用于字符串或数字。
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);
});
}