我需要将 jQuery 集转换为数组以使用 sort
和 map
等数组方法:
const result = $('.selector').toArray().map(function (el) {
const o = $(el);
return {object: o, value: o.data('value')};
}).sort(function (a, b) {
if (a.value > b.value) return 1;
if (a.value < b.value) return -1;
return 0;
}).map(el => el.object);
如您所见,结果是一个 jQuery 对象数组。
现在我需要将其转换回 jQuery 集以便操作它:
$(result).appendTo('#main');
但是 $(result)
看起来不太像 $('.selector)
并且我收到以下错误:
TypeError: e is undefined
最佳答案
我宁愿使用 append
而不是使用 appendTo
,正如您在文档中看到的那样,它的签名也接受数组: http://api.jquery.com/append/
htmlString or Element or Text or Array or jQuery DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
因此,不要使用:$(result).appendTo('#main');
,只需使用:
$('#main').append(result);
只要 result
是上述任何受支持类型的数组。
关于javascript - 将数组转换回 jQuery 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56002596/