2017-02-12 100 views
2

在KnockoutJS中,雙向綁定對於foreach循環中的輸入不起作用。修改文本輸入不會修改量程值。這在使用foreach循環時似乎只是一個問題。KnockoutJS在foreach循環中雙向綁定

<html> 
<body> 
    <table> 
    <tbody data-bind="foreach: users"> 
     <tr> 
      <td><span data-bind="text: firstName"></span></td> 
      <td><input data-bind="value: firstName" type="text"></span></td> 
      <td><span data-bind="text: lastName"></span></td> 
      <td><input data-bind="value: lastName" type="text"></td> 
     </tr> 
    </tbody> 
</table> 
<script src="js/libs/knockout-3.2.0.js"></script> 
<script> 
function User(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
} 

function UserListViewModel() { 
    var self = this; 

    self.users = ko.observableArray([ 
     new User("Joe", "Schmoe"), 
     new User("James", "Ronald") 
    ]); 
} 
ko.applyBindings(new UserListViewModel()); 
</script> 
</body> 
</html> 

回答

1

只是讓你User性能observable

function User(firstName, lastName) { 
    this.firstName = ko.observable(firstName); 
    this.lastName = ko.observable(lastName); 
} 

觀測是可以變更的有關通知用戶特殊的JavaScript對象,並能自動檢測依賴關係。