将jQuery对象数组转换为单个对象

时间:2021-09-13 21:19:54

I'm not sure if there is a better way to accomplish this, however I have a ul that I am filtering on the data-type value of each li element. This works fine for one filter since it starts as a ul object and then returns an array, or array-like of the correct li elements, however .find does not seem to work of the array of objects, only the single ul object. If there is an easy way to convert the li objects back to a single object for the second filter, or perhaps there is a better way to filter the array of li on the data-type value. Thank you in advance.

我不确定是否有更好的方法来实现这一点,但是我有一个ul,我正在过滤每个li元素的数据类型值。这适用于一个过滤器,因为它作为ul对象启动,然后返回一个数组,或者正确的li元素的数组,但是.find似乎不能处理对象数组,只有单个ul对象。如果有一种简单的方法可以将li对象转换回第二个过滤器的单个对象,或者可能有更好的方法来过滤数据类型值上的li数组。先感谢您。

Edit: The entire code is too long to post here, however, $data = $('#records'); is what gives me the ul and then var $filteredData = $data.find('li[data-type*= ' + $($filterType1+":checked").val() + ' ]'); is what correctly gives me the first filtered records.

编辑:整个代码太长,无法在此发布,但是,$ data = $('#records');是什么给了我ul然后var $ filteredData = $ data.find('li [data-type * ='+ $($ filterType1 +“:checked”)。val()+']');是什么正确地给了我第一个过滤记录。

With just this, I get an array of 24 items after the first filter, but then zero with a second filter even though there should be more than one. To test, I then didn't filter but just got every li with find and tried running the first filter over that array and it failed the same. So it appears as if .find cannot be run over an array.

有了这个,我在第一个过滤器后得到一个包含24个项目的数组,但是在第二个过滤器后为零,即使应该有多个过滤器。为了测试,我然后没有过滤但只是让每个li都找到并尝试在该阵列上运行第一个过滤器并且它失败了。所以看起来好像.find无法在数组上运行。

This works:

$data = $('#records');  
var $filteredData = $data.find('li[data-type*= ' + $($filterType1+":checked").val() + ' ]');

These both fail:

这两个都失败了:

$data = $('#records');  
var $filteredData = $data.find('li[data-type*= ' + $($filterType1+":checked").val() + ' ]');  
$filteredData = $filteredData.find('li[data-type*= ' + $($filterType2+":checked").val() + ' ]');

$data = $('#records');  
var $filteredData = $data.find('li');  
$filteredData = $filteredData.find('li[data-type*= ' + $($filterType1+":checked").val() + ' ]');

1 个解决方案

#1


1  

You are using find incorrectly. You want jQuery's filter instead. When you call

您正在使用find错误。你想要jQuery的过滤器。你打电话的时候

$filteredData = $filteredData.find('li[data-type*=x]');

It searches the children of each element in filteredData. It does not search the elements of filteredData itself.

它搜索filteredData中每个元素的子元素。它不会搜索filteredData本身的元素。

http://jsfiddle.net/YfSMB/

#1


1  

You are using find incorrectly. You want jQuery's filter instead. When you call

您正在使用find错误。你想要jQuery的过滤器。你打电话的时候

$filteredData = $filteredData.find('li[data-type*=x]');

It searches the children of each element in filteredData. It does not search the elements of filteredData itself.

它搜索filteredData中每个元素的子元素。它不会搜索filteredData本身的元素。

http://jsfiddle.net/YfSMB/