jQuery $('.class').each()有多少个项目? [英] jquery $('.class').each() how many items?

查看:151
本文介绍了jQuery $('.class').each()有多少个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jquery选择器遍历一组项目时,是否有办法找出集合中有多少项目?

When looping over a group of items using jquery selectors is there a way to find out how many items there are on the collection?

推荐答案

如果您使用链式语法:

$(".class").each(function() {
    // ...
});

...我认为each函数中的代码没有任何(合理的)方式可以知道有多少项. (不合理方法将涉及重复选择器并使用index.)

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

但是很容易使集合可用于您在each中调用的函数.这是一种方法:

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

作为一个令人费解的选项,您可以将jQuery对象转换为数组,然后使用数组的forEach.传递给forEach的回调的参数是所访问的条目(jQuery为您提供this second 参数),该条目的索引以及您所使用的数组调用它:

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

假设至少有一个模糊的现代JavaScript引擎和/或Array#forEach的填充程序.

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

或者为此,给自己一个新工具:

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

用法:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

这篇关于jQuery $('.class').each()有多少个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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