敲除不将数组的索引值传递给视图模型
Knockout not passing index value of the array to the view model
我的 foreach
绑定中有一个按钮
<button class="Button" type="button" data-bind="text: $root.UploadFile,
event: { click: function (data, e) {e.preventDefault(); $('#upload').click();}}"></button>
当我点击按钮时,我会调用以下内容
<input id="upload" type="file" style="width: 100%; display: none"
data-bind="event: { change: function(a,b){ $root.FileChanged($index,a,b)} }" />
在视图模型中,我有这个功能
private FileChanged = (index,vm, evt) => {
}
然而当函数被调用时,数组的索引总是“0”。我正在尝试通过 $index
.
获取 foreach
数组的索引
这是因为您的 foreach
中的所有 input
都具有相同的 id="upload"
。当您单击任何按钮时,它总是会触发第一个 input
。这就是为什么你每次都变成零的原因。因此,使用 attr
绑定根据 index()
更改输入的 id
。现在 input
s 的 ID 为“upload0”、“upload1”等。您还需要更改 click
绑定触发各自的ids:
const viewModel = function() {
const self = this;
self.array = ko.observableArray([0, 1]);
self.FileChanged = (index) => {
alert(index);
}
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: array -->
<button type="button" data-bind="event: { click: function (data, e) {e.preventDefault(); $('#upload' + $index()).click();}}">Upload</button>
<input type="file" style="width: 100%; display: none" data-bind="attr: {id:'upload' +$index() }, event: { change: function(a,b){$root.FileChanged($index(),a,b)} }" />
<!-- /ko -->
我的 foreach
绑定中有一个按钮
<button class="Button" type="button" data-bind="text: $root.UploadFile,
event: { click: function (data, e) {e.preventDefault(); $('#upload').click();}}"></button>
当我点击按钮时,我会调用以下内容
<input id="upload" type="file" style="width: 100%; display: none"
data-bind="event: { change: function(a,b){ $root.FileChanged($index,a,b)} }" />
在视图模型中,我有这个功能
private FileChanged = (index,vm, evt) => {
}
然而当函数被调用时,数组的索引总是“0”。我正在尝试通过 $index
.
foreach
数组的索引
这是因为您的 foreach
中的所有 input
都具有相同的 id="upload"
。当您单击任何按钮时,它总是会触发第一个 input
。这就是为什么你每次都变成零的原因。因此,使用 attr
绑定根据 index()
更改输入的 id
。现在 input
s 的 ID 为“upload0”、“upload1”等。您还需要更改 click
绑定触发各自的ids:
const viewModel = function() {
const self = this;
self.array = ko.observableArray([0, 1]);
self.FileChanged = (index) => {
alert(index);
}
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: array -->
<button type="button" data-bind="event: { click: function (data, e) {e.preventDefault(); $('#upload' + $index()).click();}}">Upload</button>
<input type="file" style="width: 100%; display: none" data-bind="attr: {id:'upload' +$index() }, event: { change: function(a,b){$root.FileChanged($index(),a,b)} }" />
<!-- /ko -->