jquery $ ('.class' ).each() 有多少项?

标签 jquery jquery-selectors

当使用 jquery 选择器循环一组项目时,有没有办法找出集合中有多少个项目?

最佳答案

如果您使用链式语法:

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

...我认为 each 函数中的代码没有任何(合理的)方法来知道有多少项。 (不合理的方法包括重复选择器和使用索引。)

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

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

作为一个有点复杂的选项,您可以将 jQuery 对象转换为数组,然后使用该数组的 forEach。传递给 forEach 回调的参数是正在访问的条目(jQuery 为您提供 this第二个 参数),该条目的索引以及您调用它的数组:

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

这假设至少有一个模糊的现代 JavaScript 引擎和/或 Array#forEach 的垫片。

或者就此而言,给自己一个新工具:

// 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() 有多少项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5148509/

相关文章:

javascript - 如何修复 Bootstrap 中的导航栏和轮播图像 slider

javascript - 无法覆盖对象/类上的 toString

jquery - 等待结果时使用动画 .gif .load()

jQuery 如何测试此 <a> 是否具有 href 属性

jquery - 在jquery中使while div可点击时需要获取rel属性和href属性

javascript - 如何实现实时更新预览(例如 Stack Overflow 帖子)?

JavaScript URL 解码功能

jquery - 仅当子 Div 有类时如何编写 jQuery

javascript - 使用 jQuery 从 CSS href 中查找服务器名称

jQuery 悬停下拉菜单不适用于 CMS