简体   繁体   中英

Knockout list with jquery event

Why event does not occur on items when I am changing their values?

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

Knockout generates new html upon applying foreach bindings, so you need to register your event globally, just like option 1 or you can do the neet binding of knockout just like in option 2. I recommend option 2 to use knockout bindings.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM