【发布时间】:2023-02-21 01:09:06
【问题描述】:
我的页面上有一个动态构建的表格,其中包含可编辑的数据字段。该表看起来像这样:
<tr>
<td class="identifier">1</td>
<td class="c1"><input type="number" data-id="123" value="123" /></td>
<td class="c2"><input type="number" data-id="456" value="456" /></td>
</tr>
<tr>
<td class="identifier">2</td>
<td class="c1"><input type="number" data-id="321" value="321" /></td>
<td class="c2"><input type="number" data-id="654" value="654" /></td>
</tr>
我在所有 tr 元素上使用 jQuery .each() 循环,并尝试将每个输入的值与 data=id 进行比较(data-id 在服务器上设置为等于框的初始值)所以我可以在用户单击按钮时保存更改的值。
我的函数看起来像这样:
$('tr').each(function (index, element) {
var idToSave = $(element).children('.identifier').first().text();
var toSave = false;
var $cone = $(element).children('td.pup input[type=number]').first();
var $ctwo = $(element).children('td.van input[type=number]').first();
var x = $cone.text();
alert('Text: ' + x);
var y = $cone.val();
alert('Val: ' + y);
var z = $cone.data("id");
alert('Data: ' + z);
if ($cone.text() != $cone.data("id")) {
toSave = true;
}
if (toSave) {
//Do an ajax call to the save method, passing in values
}
});
当我运行我的 jQuery each() 函数时,我正确地看到了标识符(通过我已经删除的警报验证)但是变量 x、y 和 z 都返回为未定义。我已经确认变量名称在我的页面中是唯一的(它们在我的实际页面中不是 x、y、z,只是这个简化版本)并且我已经尝试了许多版本的代码,包括使用 .attr("data- id") 和 .dataset.id 从我的输入中提取数据。我觉得我缺少一些简单而明显的东西。
任何人都可以提供任何建议吗?
【问题讨论】: