为什么在更改值时项目不会发生事件?
$(".target").change(function () {
alert($(".target").val());
});
function MyViewModel() {
var self = this;
self.items = ko.observableArray();
self.items.push({ name: 'Jhon' });
self.items.push({ name: 'Smith' });
}
ko.applyBindings(new MyViewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<h2>Index</h2>
<table>
<thead>
<tr>
<th>Passenger name</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><input class="target" data-bind="value: name" /></td>
</tr>
</tbody>
</table>
&#13;
答案 0 :(得分:2)
Knockout在应用foreach
绑定时生成新的html,因此您需要全局注册event,就像选项1一样,或者您可以像选项2一样对敲除进行绑定。
我建议选项2使用敲除绑定。
$(document).on('change',".target",function () {
alert('option 1 - ' + $(this).val());
});
function MyViewModel() {
var self = this;
self.items = ko.observableArray();
self.items.push({ name: 'Jhon' });
self.items.push({ name: 'Smith' });
self.alert = function(data, e){
alert('option 2 - ' + data.name);
};
}
ko.applyBindings(new MyViewModel(), document.getElementById('tblSample'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<h2>Index</h2>
<table id="tblSample">
<thead>
<tr>
<th>Passenger name</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><input class="target" data-bind="value: name, event:{change:$parent.alert}" /></td>
</tr>
</tbody>
</table>
&#13;