我有以下代码来填充表单上的下拉框。该代码似乎可以正常工作,但是会引发错误“ 无法读取未定义的属性ID ”。
jquery
function LoadAnnualCredits() {
try {
var $dropdown = $("#creditQty");
$dropdown.empty();
var arrayList = [
{ "Id": 5000, "Name": "5,000" },
{ "Id": 10000, "Name": "10,000" }
];
for (var i = 0; i <= arrayList.length; i++) {
$dropdown.append($("<option />").val(arrayList[i].Id).text(arrayList[i].Name));
}
}
catch (err) {
alert(err);
}
}
剃刀查看代码
@Html.DropDownListFor(m => m.NumCredits, Model.CreditQty, "Choose Qty", new { @class = "form-control", @id = "creditQty", @style = "width: 160px; height: 36px; line-height: 36px; padding: 4px;", @onchange = "CreditQtyChanged(this.value);" })
我尝试使用forEach方法。没有错误消息,但由于某些奇怪的原因,它使我在下拉列表中有重复的项目:
5,000
5,000
10,000
10,000
function LoadAnnualCredits() {
try {
var $dropdown = $("#creditQty");
$dropdown.empty();
let arrayList = [
{ "Id": 5000, "Name": "5,000" },
{ "Id": 10000, "Name": "10,000" }
];
arrayList.forEach(function (e) {
$dropdown.append($('<option><option/>').val(e.Id).text(e.Name));
});
}
catch (err) {
alert(err);
}
}
答案 0 :(得分:2)
您的错误可能是FOR循环的一个条件,它是(i <= arrayList.length),更改为(i