我无法弄清楚这里的问题是什么。当我在 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/