我正在调用WEB服务并获取JSON数据。之后使用knockout Js我绑定到一个表中。之后当用户在文本bax中键入内容时,它会过滤数据并在UI中显示。但目前它不起作用。请找到以下代码。
<script src="../../Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-3.3.0.js"></script>
@{
ViewBag.Title = "AllTasks";
}
<script type="text/javascript">
var viewModel;
var url = 'http://localhost:22653/api/AllTasks';
$(document).ready(function () {
debugger;
var FAJobViewModel = function () {
var self = this;
self.Parameters = ko.observableArray();
var AllTask = JSON.parse(readJSON(url));
function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};
self.Parameters = ko.observableArray(AllTask);
self.query = ko.observable('');
self.search = function (value) {
self.JobIDParameters = ko.observableArray();
debugger;
for (var x in AllTask) {
if (AllTask[x].JobNumber.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
self.JobIDParameters.push(AllTask[x]);
}
}
self.Parameters = self.JobIDParameters;
};
}
viewModel = new FAJobViewModel();
viewModel.query.subscribe(viewModel.search);
ko.applyBindings(viewModel, document.getElementById("AllTask"));
}
);
</script>
<div id="AllTask" class=" container-fluid" style="margin-top:50px">
<span>JobId</span><input id="txtSearch" placeholder="Search…" type="search" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off">
<input type="button" id="btnSearch" value="Search" " />
<table border="1">
<thead>
<tr>
<th>Job Id</th>
<th>Requestor</th>
<th>Test Name</th>
<th>Priority</th>
<th>CreatedDate</th>
</tr>
</thead>
<tbody data-bind="foreach:Parameters" class=" container-fluid">
<tr>
<td><span data-bind="text:JobNumber"></span></td>
<td><span data-bind="text:Requestor"></span></td>
<td><span data-bind="text:TaskAbbreviation"></span></td>
<td><span data-bind="text:Priority"></span></td>
<td><span data-bind="text:CreatedDate"></span></td>
</tr>
</tbody>
</table>
</div>
答案 0 :(得分:0)
存在问题,您要分配结果过滤数据,您需要避免使用=
并使用()
约定,这将保持双向绑定完整。
viewModel:
self.Original= ko.observableArray(AllTask);
self.Parameters = ko.observableArray(AllTask);
self.search = function (value) {
if(!value){self.Parameters(self.Original())}
var arr= [];
ko.utils.arrayForeach(self.Original(),function(item){
if (item.JobNumber().toLowerCase().indexOf(value.toLowerCase())>= 0)
{
arr.push(item);
}
});
self.Parameters(arr);
};
我对正确的功能做了一些小改动。希望有所帮助。