javascript - jQuery if语句在for循环中不起作用

标签 javascript jquery arrays for-loop each

我无法弄清楚这里的问题是什么。当我在 IF 语句中使用 '#account-funding-'+i 但与 '#account-funding-0' 一起使用时它不起作用。我需要能够遍历未知数量的对象数组。我做错了什么?

HTML * 页面上可以有 X 个 .funding-content div。每个带 -0 的 ID 都会从 js 递增

<form id="accountform" name="accountForm">

 <div class="funding-content funding-selected-0">
   <div class="container">
    <h3>Funding for [account selected]</h3>

     <div class="funding-type-transfer" id="funding-type-transfer-0">

       <div class="form-inputs">
         <div class="lx-grid lx-grid--gutters">
           <div class="lx-grid__cell lx-grid__cell--1-2--above-md">
             <label for="account-funding-0">Routing Number</label>
             <input id="account-funding-0" type="text" maxlength="9">
           </div>
         </div>
       </div>
     </div>
   </div>
 </div>
</form>

不起作用:

var amountOfAccounts = $( '#account-form .funding-content' ).length;

for ( i = 0; i <= amountOfAccounts; i++ ) {

    if ( $( '#account-funding-'+i ).val() == '' ) {
        document.getElementById( 'account-funding-'+i ).setCustomValidity( 'Routing Number is a required field.' );
    }
}

作品:

var amountOfAccounts = $( '#account-form .funding-content' ).length;

for ( i = 0; i <= amountOfAccounts; i++ ) {

    if ( $( '#account-funding-0' ).val() == '' ) {
        document.getElementById( 'account-funding-'+i ).setCustomValidity( 'Routing Number is a required field.' );
    }
}

最佳答案

很明显,索引没有匹配某处的元素。但是,您不需要这样做。 JQuery 提供了一个 .each() 循环遍历对象的方法,因此您不必担心任何这些:

$( '#account-form .funding-content' ).each(function(index, element){
   if(element.val() !== ""){
      // Do something
   }
});

关于javascript - jQuery if语句在for循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50258831/

相关文章:

javascript - hapi.js Cors 飞行前不返回 Access-Control-Allow-Origin header

jquery - Font Awesome 图标不会移动

javascript - JS/JQ : Schrodinger's array? 一个数组怎么可以同时为空和不为空?

c - Fgets 在每次调用时重写字符串数组位置 [0] 上的最后一行

java - 链表数组

javascript - 如何从对象构建查询字符串?

javascript - 在 Highcharts 条形图中将数据标签居中

javascript - 如何为 HTML 属性/选择器创建全局命名空间或变量?

jquery - 在淡出时重新启动 jquery.fadeOut()

c++ - 程序可以掷 2 个骰子 36000 次