2016-03-09 55 views
1

为什么事件不会发生在项目上,当我改变他们的价值?jQuery事件敲除列表

$(".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>

回答

2

淘汰赛经施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'));
<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>