我需要绑定html&#39;选择&#39; (下拉列表)如下。当我尝试将以下代码绑定到<tbody data-bind="foreach: obtainedMarksArr">
代码之外时,它运行良好。但是您可以在下面的HTML代码中看到,当我们将它放在<tbody data-bind="foreach: obtainedMarksArr">
代码中时,它会出现以下错误:
错误:&#34; 0x800a1391 - JavaScript运行时错误:&#39; gettingMarksArr&#39;未定义&#34;。
------------------------ Page-Code -------------------- ---------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.js"></script>
<script src="Scripts/knockout-2.3.0.js"></script>
<link href="Content/myTestStyleSheet1.css" rel="stylesheet" />
<script type="text/javascript">
var uri = 'api/students';
function AppViewModel(item) {
var self = this;
self.obtainedMarksArr = ko.observableArray();
for (var i = 0; i < item.ObtainedMarksList.length; i++) {
self.obtainedMarksArr.push({ course: item.ObtainedMarksList[i].courseName, totalmarks: item.ObtainedMarksList[i].TotalMarks, obtainedMarks: item.ObtainedMarksList[i].ObtainedMarks });
}
}
//---------------------------------------------------------------------------------------------
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
//Apply binding here:
ko.applyBindings(new AppViewModel(data));
});
});
</script>
</head>
<body>
<div id="div1">
<table class="marginTable2">
<thead>
<tr class="ThColor">
<th class="textCenter ThColor topThColor" colspan="4">Obained Marks List</th>
</tr>
<tr class="ThColor">
<th class="textLeft ThColor">Course</th>
<th class="textLeft ThColor">Total Marks</th>
<th class="textLeft ThColor">Obtained Marks</th>
</tr>
</thead>
<tbody data-bind="foreach: obtainedMarksArr">
<tr class="TrColor">
<td class="textLeft"><select data-bind="options: obtainedMarksArr, optionsText: 'course'"></select></td>
<td class="textLeft"><input data-bind="value: totalmarks" /></td>
<td class="textLeft"><input data-bind="value: obtainedMarks" /></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
我错过了什么。我非常感谢你的回答。
感谢。
答案 0 :(得分:3)
在foreach: obtainedMarskArr
内,您的上下文已更改为此内容。
这里的<select data-bind="options: obtainedMarksArr
是问题,应该是<select data-bind="options: obtainedMarks
,因为您现在正在处理这些对象,对于您创建的每个tr
{
course: item.ObtainedMarksList[i].courseName,
totalmarks: item.ObtainedMarksList[i].TotalMarks,
obtainedMarks: item.ObtainedMarksList[i].ObtainedMarks
}
或者,如果您需要获取下拉列表来获取MarsSrr,您可以执行:<select data-bind="options: $root.obtainedMarksArr