我使用循环,并通过按钮将数据添加到表中。 因此,每次它都会为我创建 5 个单元格,但我只需在单击按钮后追加一次数据。
代码:
$('.next').on('click', function () {
$('.changeoverTable').show();
var arrNumber = new Array();
$('input[type=text]').each(function (i) {
arrNumber.push($(this).val());
$(".changeoverTable > tbody").append('<tr><td>Data</td><td>' + arrNumber[i] + '</td></tr>');
})
});
body {
background: #f5f5f5;
}
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" placeholder="Enter number of data"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
<input type="text" placeholder="Enter number of nest"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
<table class="changeoverTable hide">
<thead>
<tr>
<th colspan="3">Table</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
如您所见,每次单击“确定”后,我都会得到 5 行,但我只需要每个输入字段中的一行。
最佳答案
只需执行 if 条件 if(arrNumber[i]){
检查值是否存在。
$('.next').on('click', function () {
$('.changeoverTable').show();
var arrNumber = new Array();
$(".changeoverTable > tbody").html('');
$('input[type=text]').each(function (i) {
arrNumber.push($(this).val());
if(arrNumber[i]){
$(".changeoverTable > tbody").append('<tr><td>Data</td><td>' + arrNumber[i] + '</td></tr>');
}
})
});
body {
background: #f5f5f5;
}
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" placeholder="Enter number of data"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
<input type="text" placeholder="Enter number of nest"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
<table class="changeoverTable hide">
<thead>
<tr>
<th colspan="3">Table</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
关于javascript - jQuery 如何在循环中仅追加一次数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107670/