【发布时间】:2023-03-10 02:34:01
【问题描述】:
我使用 jquery 向页面动态添加一个表,该表包含 5 个下拉菜单。我正在尝试填充已动态添加的行上的下拉列表之一的值,但是,我无法实现它。
这是我的表格,为了简单起见,我删除了不必要的字段:
<table class="table" id="1" order-month="2021-05-01T00:00:00">
<thead>
<tr>
<th scope="col">
<select class="form-select form-control mb-2 mr-sm-2" id="ItemList">
<option selected="">Select Item</option>
</select>
</th>
</tr>
<tr>
<th scope="col">Item</th>
<th scope="col">Day Part</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="form-select form-control mb-2 mr-sm-2" id="ClassificationList">
<option selected="">Select Classification</option>
</select>
</td>
<td>
<select class="form-select form-control mb-2 mr-sm-2" id="DayValueList">
<option selected="">Select Day Value</option>
</select>
</td>
</tr>
</tbody>
</table>
当在屏幕上按下按钮时,该表是通过 jquery 动态添加的,当我从 ItemList 选择列表中选择一个项目时,将调用一个 ajax 方法,该方法反过来从服务器检索分类。然后我尝试填充分类列表选择列表,如下所示:
$.ajax({
type: 'POST',
data: formData,
url: '@Url.Page("product", "getitemclassifications")',
success: function (result) {
console.log(result);
var $dropdown = $("$('table[id=1] > tbody > tr > td > select#ClassificationList')");
$.each(result.classifications, function () {
$dropdown.append($("<option />").val(this.id).text(this.name));
});
},
error: function (result) { }
});
出于测试目的,我在 ajax 方法中硬编码了表的 ID。
但是,我收到以下错误:
语法错误,无法识别的表达式:$('table[id=1] > tbody > tr > td > select#ClassificationList')
谁能指出正确的方向,让我了解如何定位一个动态添加的选择列表,然后用给定的值填充它?
【问题讨论】:
-
为什么不直接使用
$("select#ClassificationList")? -
页面上已经有一个表,它是我们在向页面添加新表时克隆的骨架表(隐藏在用户视线之外)。当我尝试您的建议时,它会填充骨架表上的下拉列表,而不是新添加的表,因此我需要明确地针对动态添加的表上的选择列表。