jquery $(‘ class’) each()有多少项?

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

解决方法

如果您使用链接语法:
$(".class").each(function() {
    // ...
});

…我不认为每个函数中的代码有什么(合理的)方式来知道有多少项目。 (不合理的方式将涉及重复选择器和使用索引。)

但是,很容易使收集可用于每个调用函数。这是一种方法

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

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

$(".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,me);
    });
};

用法

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...