首页 > 解决方案 > 在 Array JS 上完成

问题描述

我有一个数组var $test = $(".main-div").find(".some-class img");

如何if使用 JS complete正确创建语句?

if ($test.complete) {} 

只有当数组中的所有元素(img)时,我才需要执行一个函数complete == true

// 上面的例子不起作用,因为它是 jQuery 对象,并且它是一个数组

标签: javascriptjquery

解决方案


true如果every与您的选择器匹配的图像已被浏览器完全加载,则将返回以下内容:

[...document.querySelectorAll(".main-div .some-class img")].every(i=>i.complete)

用作 - 语句中的条件if

if ([...document.querySelectorAll(".main-div .some-class img")].every(i=>i.complete)) { 
  // do stuff 
}

[...]由annodeList返回,因此您可以在其上使用数组方法。它被称为阵列传播。document.querySelectorAllarrayevery()

你也可以做

Array.from(document.querySelectorAll(".main-div .some-class img")).every(i=>i.complete)

或者,如果您需要支持支持every()但不支持的浏览器[...]

Array.prototype.every.call(document.querySelectorAll(".main-div .some-class img"), function(i) { return i.complete })

推荐阅读