带有jquery事件的淘汰列表

时间:2016-03-09 00:01:43

标签: javascript jquery knockout.js

为什么在更改值时项目不会发生事件?



$(".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;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

Knockout在应用foreach绑定时生成新的html,因此您需要全局注册event,就像选项1一样,或者您可以像选项2一样对敲除进行绑定。 我建议选项2使用敲除绑定。

&#13;
&#13;
$(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;
&#13;
&#13;