jquery - 使用模型中的元素列表在循环上处理 JQuery .change()
问题描述
我有一个视图,其中有下拉级联元素如果您在下拉列表中选择一个元素,它将获得一个列表并使用结果元素填充另一个下拉列表。如果我只有一对级联下拉列表,它可以工作,但是,如果我添加多个级联下拉列表,它就不起作用,它只是将元素添加到第一个依赖下拉列表,我知道这是因为禁止使用相同的 ID,但是,我不知道如何使它成为可能。(有多个级联下拉菜单)
Ajax 代码如下:
$(document).ready(function () {
$("#CC").change(function () {
$("#CustomerId").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetCustomersByCC")',
dataType: 'json',
data: { id: $("#CC").val() },
success: function (states) {
$.each(states, function (i, CustomerId) {
$("#CustomerId").append('<option value="' + CustomerId.Value + '">' +
CustomerId.Text + '</option>');
});
},
error: function (ex) {
alert('Error getting cost centers' + ex);
}
});
return false;
})
});
在我看来:
@model List<FlexCart.Data.Context.OrderItem>
@for (int i = 0; i < Model.Count(); i++)
{
@Html.DropDownListFor(model => model[i].CCId,
IEnumerable<SelectListItem>)ViewBag.CCIds,
htmlAttributes: new { id = "CC", @class = "form--control"})
@Html.DropDownListFor(model => model[0].CustomerId,
new SelectList(string.Empty, "Value", "Text"),
htmlAttributes: new { id = "CustomerId", @class = "form-control"})
}
解决方案
您应该使用相对选择器。jQueryclosest
和find
方法会派上用场。
首先,将每一行包装在一个容器 div 中。同时删除Id
选择器,因为重复Id
的 s 是无效的。为两个下拉菜单提供一个 css 类,我们稍后将用于相对选择器。
@for (int i = 0; i < Model.Count(); i++)
{
<div class="item-row">
@Html.DropDownListFor(model => model[i].CCId, ViewBag.CCIds as List<SelectListItem>,
new { @class = "ccid form--control" })
@Html.DropDownListFor(model => model[0].CustomerId,
new SelectList(string.Empty, "Value", "Text"),
new { @class = "customer form-control" })
</div>
}
现在,在您的更改事件中
$(document).ready(function () {
$("SELECT.ccid").change(function() {
var val = $(this).val();
var $customer = $(this).closest(".item-row").find("SELECT.customer");
$customer.empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetCustomersByCC")',
data: { id: val },
success: function(states) {
var options = '';
$.each(states, function(i,c) {
options+= '<option value="' + c.Value + '">' + c.Text + '</option>';
});
$customer.append(options);
},
error: function(ex) {
alert('Error getting cost centers' + ex);
}
});
});
});
选择$(this).closest(".item-row")
器为我们提供了包装器 div,.find("SELECT.customer")
并将在该容器 div 中提供客户选择元素。
推荐阅读
- php - 调用 Lambda 客户端返回未知错误
- python - 在函数调用中添加要设置的项目?
- node.js - DynamoDB = 为什么我在传递有效值时收到“提供的关键元素与架构不匹配”错误?
- r - 渲染带有旋转的R脚本时如何传递参数?
- angular - 使用 ng-select 插入动态模板
- group-by - 如何创建动态汇总表以包含在 DAX 度量中?
- excel - 设置右页脚
- makefile - Makefile 中没有先决条件的隐式规则
- python - session.query 中的 Sqlalchemy 传递参数
- java - 为什么我的 twitter4j maven 依赖项不包括 TwitterStreamFactory?