【问题标题】:Verify true with array用数组验证真
【发布时间】:2026-01-16 23:45:01
【问题描述】:

我正在尝试创建一个循环来验证 .offer_no 跨度中找到的所有数字是否不 = 0,如果所有数字 = 0,则返回 true。目前我已经写过,但我不确定如何创建验证循环。

$(".offers_container").find(".offer_no span").text()

Console Screenshot

【问题讨论】:

  • 您可以将元素选择器语句分配给一个变量,例如:let elementArray = $(".offers_container").find(".offer_no span").text();然后使用循环结构遍历数组并查看每个元素的值或您要查找的任何内容(查看数组的结构,控制台记录其内容)然后编写您想要的任何比较。请注意,在 javascript 中有一些简洁的循环结构,例如 .every -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。下次您发布问题时,请在您尝试过的内容中添加更多内容。 GL!

标签: javascript jquery arrays loops verify


【解决方案1】:

像这样:

//all zeros exaple:

   function is_all_zeros(){                                       //default function return
     var out=true;
     if($(".offers_container").find(".offer_no span").length<1){  //if not found elements return false
     	 out=false;
     }
     $(".offers_container").find(".offer_no span").each(function(){
     	var this_text_int=parseInt($(this).text(), 10);           //integer value of found spin
        if(this_text_int!=0){                                     //found value not 0
        	 out=false;
        }
     });
     return out;
   }
   
   
   
   console.log(is_all_zeros());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="offers_container">
   <div class="offer_no">
       <span>0</span>
   </div>
</div>

<div class="offers_container">
   <div class="offer_no">
       <span>0</span>
   </div>
</div>

//not all zerros example:

   function is_all_zeros(){                                       //default function return
     var out=true;
     if($(".offers_container").find(".offer_no span").length<1){  //if not found elements return false
     	 out=false;
     }
     $(".offers_container").find(".offer_no span").each(function(){
     	var this_text_int=parseInt($(this).text(), 10);           //integer value of found spin
        if(this_text_int!=0){                                     //found value not 0
        	 out=false;
        }
     });
     return out;
   }


   console.log(is_all_zeros());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="offers_container">
   <div class="offer_no">
       <span>0</span>
   </div>
</div>

<div class="offers_container">
   <div class="offer_no">
       <span>4</span>
   </div>
</div>

【讨论】:

  • 非常感谢您的帮助。我仍然是初学者,仍在努力学习基础知识。你最好!