我已经与knockoutjs结合了。
<tbody data-bind="foreach: contracts">
<tr>
<td data-bind="text: Number"></td>
<td data-bind="text: BusinessName"></td>
<td> <div> I need load content to this div with ajax, url depends on $data.id value </div> </td>
</tr>
</tbody>
如您所见,最后一个td内有div,我需要将$("div").load("/Controller/Action/$data.Id")
加载到此div的内容,其中$data
是来自foreach
周期的元素。
有人可以提供建议吗?
谢谢。
答案 0 :(得分:1)
您应该向视图模型添加一个属性,您可以通过ajax调用填充该属性。像这样:
function Contract(number, name) {
var self = this;
self.number = ko.observable(number);
self.businessName = ko.observable(name);
self.content = ko.observable(); // note: you could provide a default value
// while loading if you want, or better might
// be an "isLoading" observable
// load your ajax content:
// eg. $.ajax(yourUrl, { data: ....
// your callback would actually populate self.content
// Just faking it here with a timeout:
setTimeout(function() {
self.content("foo");
}, 1000);
}
function ViewModel() {
var self = this;
self.contracts = ko.observableArray();
}
var vm = new ViewModel();
vm.contracts.push(new Contract("1", "2"));
vm.contracts.push(new Contract("a", "b"));
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<tbody data-bind="foreach: contracts">
<tr>
<td data-bind="text: number"></td>
<td data-bind="text: businessName"></td>
<td>
<div data-bind="text: content"></div>
</td>
</tr>
</tbody>
</table>