【发布时间】:2023-04-05 07:06:01
【问题描述】:
我有一个按钮,当使用单击它时,它会添加两个下拉列表,第二个的值取决于用户从第一个中选择的内容(值来自数据库),他可以根据需要添加多个下拉列表,所以我需要识别每个用户选择, 所以我这样做: 当他点击按钮添加时
var Incremental = 0;
$("#add-newProduct").on("click", function () {
Incremental++;
LoadCategories();
var htmlString = `
<tr>
<td>
<select class="category-DropDownList`+ Incremental +`"> </select>
</td>
<td>
<select class="product-DropDownList`+ Incremental +`"></select>
</td>
<td>
<input id="product-price`+ Incremental +`" type="text" disabled />
</td>
<td>
<input id="product-quantity`+ Incremental +`" type="text" disabled />
</td>
<td>
<a class="delete-button`+ Incremental +` button is-danger">remove product</a>
</td>
</tr>
`;
$("#product-rows").append(htmlString);
});
function LoadCategories() {
$.getJSON('@Url.Action("GetAllCategories", "Categories")', function (result) {
console.log(result);
$(".category-DropDownList" + Incremental).html("");
$(".category-DropDownList" + Incremental).append("<option value=''>no thing selected</option>");
for (var i = 0; i < result.length; i++) {
$(".category-DropDownList" + Incremental).append("<option value=" + result[i].ID + ">" + result[i].Name + "</option");
}
});
然后当他从 .category-DropDownList 中选择一个值时
$("#product-rows").on("change", ".category-DropDownList" + Incremental, function () {
showProducts($(this).val());
});
function showProducts(val)
{
console.log(val);
$.getJSON('@Url.Action("GetProductsByCategoryId", "Products")' + "/" + val, function (result) {
$(".product-DropDownList" + Incremental).html("");
var data = result;
console.log(data);
$(".product-DropDownList" + Incremental).append("<option value=''>no thing selected</option>");
for (var i = 0; i < data.length; i++) {
$(".product-DropDownList" + Incremental).append("<option value=" + data[i].ID + ">" + data[i].Name + "</option");
}
});
}
所以问题在这里: $("#product-rows").on("change", ".category-DropDownList" + Incremental, function () 如何将增量值与 .category-DropDownList 连接起来
【问题讨论】:
-
我认为您不必包含 + 增量部分,因为 $(this).val();选择器足以选择具有声明类的当前元素。
-
如果我这样做,并使用 add htmlString 假设 5 次,那么每次他都会尝试从类别下拉列表中进行选择,这将影响所有产品下拉列表。
-
为了防止这种情况,使用next('.classname'),这样它就不会影响同一个类的其他元素。另外,我建议在您的问题中添加一个 sn-p,以便我们对其进行测试。
标签: javascript jquery frontend web-frontend