如何在JavaScript中获取动态添加表格行的行ID及选中值
动态表格行的Select值变化事件处理方案
问题描述
我在应用中通过循环为动态添加的表格行分配ID,当前正在视图里创建采购订单(Purchase Order)并添加表格行。需求是当<Select>控件的值发生变化时,通过JavaScript获取该行的ID以及选中的选项ID,以便发送至后端控制器,请问如何实现?
当前代码
var counter = 1; $(function () { $("#add").click(function () { var newRow = $( '<tr id="tablerow' + counter + '"> ' + "<td>" + '<label id="CountItems"><strong>' + counter + "</strong></label>" + "</td>" + '<td width="40%">' + '<select class="form-select js-dropdown" name="Item_Id[' + counter + ']" id="ItemId' + counter + '" required="required" ' + "</select>" + "</td>" + '<td width="10%">' + '<input type="text" class="form-control" name="Qty[' + counter + ']" value="1" id="Qty' + counter + '" required="required" />' + "</td>" + '<td width="10%">' + '<input type="text" class="form-control" name="AcidStables[' + counter + ']" value="" required="required" />' + "</td>" + '<td width="20%">' + '<input type="text" class="form-control" name="Unit_Price[' + counter + ']" value="0.00" id="UnitPrice' + counter + '" required="required" />' + "</td>" + '<td width="20%">' + '<input type="text" class="form-control" name="Line_Total[' + counter + ']" value="0.00" id="LineTotal' + counter + '" required="required" />' + "</td>" + "<td>" + '<button type="button" class="btn btn-danger" onclick="removeTr(' + counter + ');">x</button>' + "</td>" + "</tr>" ); var selectElement = newRow.find("select"); // 找到新行中的<select>元素 // 给<select>元素填充选项 dropdownOptions.forEach(function (option) { var optionElement = $("<option>").val(option.Value).text(option.Text); selectElement.append(optionElement); }); newRow.appendTo("#submissionTable"); counter++; return false; }); });
实现方案
可以通过两种方式为动态创建的<select>控件绑定值变化事件,从而获取行ID和选中的选项ID:
方式一:创建行时直接绑定事件
在填充完select选项后,直接为当前select元素绑定change事件:
// 填充选项的代码之后添加 selectElement.on('change', function() { // 获取选中的选项ID var selectedOptionId = $(this).val(); // 获取当前行的ID var rowId = $(this).closest('tr').attr('id'); // 这里可以添加发送到后端的逻辑,示例AJAX请求 /* $.ajax({ url: '/你的后端接口路径', method: 'POST', data: { rowId: rowId, itemId: selectedOptionId }, success: function(response) { // 处理成功回调 console.log('请求成功:', response); }, error: function(xhr) { // 处理错误情况 console.error('请求失败:', xhr); } }); */ // 测试输出 console.log('行ID:', rowId, '选中的选项ID:', selectedOptionId); });
方式二:使用事件委托(推荐大量动态元素场景)
利用事件委托机制,将事件绑定到表格父元素上,统一处理所有动态添加的select控件的变化事件:
在$(function () {})内部、$("#add").click事件的外部添加以下代码:
$('#submissionTable').on('change', '.js-dropdown', function() { var selectedOptionId = $(this).val(); var rowId = $(this).closest('tr').attr('id'); // 同样可以添加发送到后端的逻辑 console.log('行ID:', rowId, '选中的选项ID:', selectedOptionId); });
关键逻辑说明
$(this).closest('tr'):从当前select元素向上查找最近的<tr>元素,以此获取行的ID$(this).val():获取当前select控件选中的选项值(即你需要的选项ID)- 两种方式都能实现需求,事件委托更适合频繁添加行的场景,不需要每次创建元素都绑定事件,性能更优
内容的提问来源于stack exchange,提问作者Dev Beginner
相关产品推荐
相关产品推荐

