HTML
<tbody data-bind="foreach: arrayList">
<tr>
<td><a href="#" data-bind="click: $parent.downloadLastFile">Download</a></td>
</tr>
</tbody>
的javascript
function ItemViewModel(item){
if(!$.isEmptyObject(item)){
var self = this;
self.lastFile = ko.observable(item.file_name);
self.downloadLastFile = function(row) {
console.log(row.lastFile());
var link = document.createElement('a');
link.href = data;
link.download = row.lastFile();
document.body.appendChild(link);
link.click();
}
}
}
function MainViewModel() {
var self = this;
self.arrayList= ko.observableArray();
}
dataModel = new MainViewModel();
ko.applyBindings(dataModel);
我正在尝试点击下载文件。这段代码不起作用。有人可以查一下吗?
答案 0 :(得分:0)
self
变量。$parent
绑定中看到click
,我认为应该有一个您定义的父模型并将数据分配给ArrayList
。knockout click binding
,因此您无需再次使用jquery
点击绑定点击功能("#download_div")
。 WRONG 下面是一个如何做到的例子
示例:https://jsfiddle.net/kyr6w2x3/114/
JS:
var data = [{id:1, file_name : "file_name1"},{id:2, file_name : "file_name2"}];
function AppViewModel(){
var self = this;
self.ArrayList = ko.observableArray($.map(data, function (item) {
return new ItemViewModel(item);
}));
self.downloadLastFile = function(item) {
console.log(item.lastFile());
var link = document.createElement('a');
link.href = data;
//here you append your rootURL to the file name
link.download = item.lastFile();
document.body.appendChild(link);
link.click();
}
}
var ItemViewModel = function(data){
var self = this;
self.lastFile = ko.observable(data.file_name);
}
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);