2017-06-02 45 views
0

我試圖創建一個購物清單,用戶可以輸入物品和數量。我在列表中添加了一些項目(在代碼中),但我希望用戶使用「添加」按鈕來添加內容。如何讓用戶輸入數據到observabaleArrays

在用戶點擊添加時,添加了「新的4」。我希望這些數據是用戶輸入的。我不知道如何讓用戶輸入數據到observabaleArrays。

我對Knockout.js相當陌生,我無法找到解決方法。

<table> 
    <thead> 
     <tr> Item </tr> 
     <tr> Quantity </tr> 
    </thead> 
    <tbody data-bind="foreach: items"> 
     <tr> 
      <td data-bind="text:item"></td> 
      <td data-bind="text:quantity"></td> 
     </tr> 
    </tbody> 
</table> 

<button data-bind="click: addItem"> ADD </button> 

<script> 

    function appViewModel(){ 
      var self = this; 


     self.items = ko.observableArray([ 
      { 
       item: 'Carrot', 
       quantity : '1' 
      }, 
      { 
       item: 'Milk', 
       quantity : '2' 
      }, 
      { 
       item: 'Bread', 
       quantity : '3' 
      } 
     ]); 

     self.addItem = function(){ 
      self.items.push({item: 'New', quantity: '4'}); 
     } 
    } 

    ko.applyBindings(new appViewModel()); 
</script> 

</body> 
</html> 

回答

0

function item(item, quantity) { 
 
    var self = this; 
 
    this.item = ko.observable(item); 
 
    this.quantity = ko.observable(quantity) 
 
    
 
} 
 

 
function viewModel() { 
 
    var self = this; 
 
    this.item = ko.observable(''); 
 
    this.quantity = ko.observable(''); 
 
    this.items = ko.observableArray([ 
 
    new item('carrot', 1), 
 
    new item('milk', 2), 
 
    new item('bread', 3), 
 
    ]); 
 
    this.add = function(){ 
 
    self.items.push(new item(self.item(), self.quantity())) 
 
    } 
 
} 
 

 
var vm = new viewModel(); 
 
$(document).ready(function() { 
 
    ko.applyBindings(vm); 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <thead> 
 
    <tr> Item </tr> 
 
    <tr> Quantity </tr> 
 
    </thead> 
 
    <tbody data-bind="foreach: items"> 
 
    <tr> 
 
     <td data-bind="text:item"></td> 
 
     <td data-bind="text:quantity"></td> 
 
    </tr> 
 
    </tbody> 
 
</table> 
 

 
<p> 
 
item: <input data-bind="value: item"> 
 
</p> 
 

 
<p> 
 
quantity: <input data-bind="value: quantity"> 
 
</p> 
 
<button data-bind="click: add"> 
 
add 
 
</button>

相關問題