简体   繁体   English

在执行代码之前,如何遍历某些类的所有元素?

[英]How to loop through all elements of certain class BEFORE executing a code?

Let's say i have a class "dog". 假设我有一个“狗”类。 I have 5 elements which all have the class "dog". 我有5个元素都具有“狗”类。 I want to check if all the elements which have the class "dog" have a certain background-color. 我要检查是否所有具有“狗”类的元素都具有特定的背景色。 If they have i want to execute a certain code. 如果他们有我想执行某些代码。 I do NOT want to loop through each element and execute the code in between every iteration. 不会通过每一个元素要循环,并在每次迭代之间执行的代码。 What I want is to first check ALL the elements that do they have the certain background-color before executing a code. 我想要的是在执行代码之前先检查所有具有特定背景颜色的元素。

I tried this: 我尝试了这个:

function openBtn () {
  green = 'rgb(144, 238, 144)';

  if ($('.glassver').css('background-color') == green || $('.glasshor').css('background-color') == green || $('.glassxyz').css('background-color') == green) {
    $('#orderBtn').removeAttr('disabled', 'disabled');
    $('#orderBtn').css("background-color", "#3da669");
  } else {
    $('#orderBtn').attr('disabled', 'disabled');
    $('#orderBtn').css("background-color", 'lightgray');
  }
}

Get all the div elements which have dog class and build an array from them. 获取所有具有dog类的div元素,并从中构建一个数组。

Then use the every method of array to check your background color condition. 然后使用array的every方法检查背景色条件。 If it is true for all of them, execute your code 如果对所有人都正确,请执行代码

 const dogs = Array.from(document.querySelector('div.dog')); if (dogs.every(d => d.style.backgroundColor === 'red')) { console.log('do some code'); } 
 <div class="dog" style="background-color:red">DOG 1</div> <div class="dog" style="background-color:red">DOG 2</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM