点击按钮时如何提取动态生成表格内对应行的单元格输入值?
问题根源
- 取值逻辑错误:
<td>是单元格容器,本身没有value属性,也不会将内部输入框的内容作为自身文本存储,直接对<td>调用.text()或.val()自然拿不到有效内容,值实际存储在<td>嵌套的<input>元素上。 - 存在ID重复违规:HTML规范要求ID全局唯一,你动态生成的所有行内元素都用了相同ID(如
id="0"、id="addAltBtn"),重复ID会导致元素选择、事件绑定出现异常。
修正方案
1. 调整动态生成行的代码(移除重复ID)
删除重复的id属性,按钮事件绑定直接用类名即可:
var html = ''; // 去掉所有重复id属性,避免冲突 html += "<tr><td style='width : 1%; white-space: nowrap;'><input type='date' name='date' class='alterationsDetailDate' value='" + todayDate + "'></td>"; html += "<td><input type='text' name='problem' class='alterationsDetail maxWidth' value=''></td>"; html += "<td style='text-align : center; width : 1%; white-space: nowrap;'><input type='checkbox' name='discuss' class='form-check-input alterationsDetail' value=''></td>"; html += "<td><input type='text' name='outcome' class='alterationsDetail maxWidth' value=''></td>"; html += "<td style='width : 1%; white-space: nowrap;'><input type='button' name='addAltBtn' class='alterationsAdd btn-info' value='Add'></td></tr>"; $(html).appendTo($("#alterationsTablebody"));
2. 调整点击取值逻辑
事件绑定用按钮的类名alterationsAdd,找到当前行后直接选中内部的<input>元素取值,针对不同输入类型做对应处理:
$('#alterationsTable tbody').on('click', '.alterationsAdd', function () { // 获取当前点击按钮所在的行 var $currRow = $(this).closest('tr'); // 选中当前行所有输入元素 var $inputs = $currRow.find('input'); // 遍历提取各输入值 $inputs.each(function(index, input) { var $input = $(input); var fieldName = $input.attr('name'); var fieldValue; // 不同输入类型取值逻辑不同 if ($input.attr('type') === 'checkbox') { fieldValue = $input.is(':checked'); // 复选框取选中状态 } else { fieldValue = $input.val(); // 文本、日期输入框直接取value } // 测试输出,可根据需求替换为自己的业务逻辑 console.log(fieldName + ': ' + fieldValue); }); });
如果需要单独取某一列的输入值,比如第二列的问题内容,可直接使用以下写法:$currRow.find('td:eq(1) input').val()
内容的提问来源于stack exchange,提问作者Glyn
相关产品推荐
相关产品推荐

