微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
});

原文地址:https://www.jb51.cc/jquery/183599.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐