我正在尝试创建一个由对象组成的数组。最后完成,最后,数组具有相同数量的项目,但它们都是我的最后一个循环对象。这似乎是某种参考。我真的不知道问题出在哪里。
CodePen HTML:
<table class="table table-admin-panel table-bordered">
<tbody>
<tr>
<th>Active</th>
<th>Name</th>
<th>Price</th>
<th>Delete</th>
</tr>
<tr>
<td class="table-admin-panel-active"><input type="checkbox"></td>
<td> <input class="name" type="text" value="Example 1"></td>
<td><input type="number" value="10"></td>
<td class="table-admin-panel-remove"><i class="fa fa-times" aria-hidden="true"></i></td>
</tr>
<tr>
<td class="table-admin-panel-active"><input type="checkbox" checked=""></td>
<td> <input class="name" type="text" value="Example 2"></td>
<td><input type="number" value="20"></td>
<td class="table-admin-panel-remove"><i class="fa fa-times" aria-hidden="true"></i></td>
</tr>
<tr>
<td class="table-admin-panel-active"><input type="checkbox" checked=""></td>
<td> <input class="name" type="text" value="Example 3"></td>
<td><input type="number" value="30"></td>
<td class="table-admin-panel-remove"><i class="fa fa-times" aria-hidden="true"></i></td>
</tr>
<tr>
<td class="table-admin-panel-active"><input type="checkbox" checked=""></td>
<td> <input class="name" type="text" value="Example 4"></td>
<td><input type="number" value="40"></td>
<td class="table-admin-panel-remove"><i class="fa fa-times" aria-hidden="true"></i></td>
</tr>
</tbody>
</table>
<div class="buttons">
<button class="btn-bps btn-save">Zapisz</button>
</div>
CodePen JS:
$(document).ready(function() {
$(".btn-save").click(function(event) {
var element = new Object();
var output = new Array();
$(this).parent(".buttons").siblings("table").find("tr").each(function(index, el) {
$(this).find("td input").each(function(index2, el) {
if (index !== 0) {
if (index2 === 0) {
var checkboxStatus = $(this).prop("checked");
if (checkboxStatus === true) {
element["active"] = "1";
} else {
element["active"] = "0";
}
} else if (index2 === 1) {
element["name"] = $(this).val();
} else if (index2 === 2) {
element["value"] = $(this).val();
}
element["id"] = index - 1 + "";
}
});
output[index] = element;
});
console.log(output);
});
});
答案 0 :(得分:0)
element
在循环(.each
)之外定义并实例化,并在每次迭代时保持相同的引用。
尝试在循环中实例化它。
答案 1 :(得分:0)
您需要在第一个循环内声明元素。现在,您将在每次迭代时覆盖元素对象的值。请参阅下面的代码。
$(document).ready(function() {
$(".btn-save").click(function(event) {
var output = new Array();
$(this).parent(".buttons").siblings("table").find("tr").each(function(index, el) {
var element = new Object(); //NEW ELEMENT LOCATION
$(this).find("td input").each(function(index2, el) {
if (index !== 0) {
if (index2 === 0) {
var checkboxStatus = $(this).prop("checked");
if (checkboxStatus === true) {
element["active"] = "1";
} else {
element["active"] = "0";
}
} else if (index2 === 1) {
element["name"] = $(this).val();
} else if (index2 === 2) {
element["value"] = $(this).val();
}
element["id"] = index - 1 + "";
}
});
output[index] = element;
});
console.log(output);
});
});