我有一个数组var $test = $(".main-div").find(".some-class img");
如何在JS完成的情况下正确创建if
语句?
if ($test.complete) {}
只有当数组complete == true
中的所有元素(img)都存在时,我才需要执行函数。
//上面的例子不起作用,因为它是jQuery对象,并且是一个数组
如果浏览器完全加载了与选择器匹配的every
图像,则以下内容将返回true
:
[...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
}
[...]
使document.querySelectorAll
返回的nodeList
成为array
,因此可以对其使用数组方法every()
。它被称为数组排列。
你也可以做
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 })
您可以使用map()
获取所有完整值。然后你可以检查返回值,如果其中包括任何错误,如果没有,那么所有图像都会被加载,你可以执行你的代码:
var $test = $(".main-div").find(".some-class img");
var status = $test.map(function(i, el){
return el.complete;
}).get();
if(!status.includes('false'))
console.log(status)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-div">
<div class="some-class">
<img id="myImg" src="https://www.gstatic.com/webp/gallery/1.jpg" alt="Tree" width="107" height="98">
</div>
<div class="some-class">
<img id="myImg" src="https://www.gstatic.com/webp/gallery/2.webp" alt="Skating" width="107" height="98">
</div>
</div>