根据我的代码,我想将每一行的输入推送到每个数组。如果是第 1 行,它应该将第 1 行的所有输入值推送到数组 a1
。第二行的输入应该被推送到数组 a2
等等。
这主要是为了优化我的代码的性能,因为我的实际代码行数超过 20 行,我正在尝试如下所示但没有成功。
我希望能够知道每一行的数据(用于验证目的)
$('#check').click(function(event){
event.preventdefault;
var a1=[];var a2=[];
$("[id^=row]").find("td input").each(function(i) { a[i].push(this.value); });
$('#output').html('<h4>Pushed arrays:</h4>a1: ['+a1 +'] <br/> a2: ['+a2+']');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="row1">
<td>1</td>
<td><input type="text" value="0" size="4"></td>
<td><input type="text" size="4"></td>
<td><input type="text" size="4"></td>
<td><input type="text" value="0" size="4"></td>
</tr>
<tr id="row2">
<td>1</td>
<td><input type="text" size="4"></td>
<td><input type="text" value="1" size="4"></td>
<td><input type="text" value="0" size="4"></td>
<td><input type="text" size="4"></td>
</tr>
</table>
<button id="check">Check Values</button>
<div id="output"></div>
最佳答案
我会使用 $.map
来创建一个嵌套数组。看起来好像你想要很多行。因此,我建议使用二维数组而不是单个变量来避免重复代码。使用二维数组,您可以遍历每一行;对于单个变量,您必须为每一行手动重写相同的代码。
$('#check').click(function(event){
event.preventdefault;
var serialize = [];
$("#myTable tr").each(function () {
serialize.push($.map($(this).find("input"), function (ele) {
return ele.value;
}));
});
console.log(serialize);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>1</td>
<td><input type="text" value="0" size="4"></td>
<td><input type="text" size="4"></td>
<td><input type="text" size="4"></td>
<td><input type="text" value="0" size="4"></td>
</tr>
<tr>
<td>1</td>
<td><input type="text" size="4"></td>
<td><input type="text" value="1" size="4"></td>
<td><input type="text" value="0" size="4"></td>
<td><input type="text" size="4"></td>
</tr>
</table>
<button id="check">Check Values</button>
<div id="output"></div>
关于javascript - 动态推送基于每一行输入的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206723/