2017-04-01 83 views
1

HTMLknockout.js UL李綁定不正確

<h4>People</h4> 
<ul data-bind="foreach: people"> 
    <li>  
     <span data-bind="text: name"> </span> 
     <a href="#" data-bind="click: $parent.removePerson">Remove</a> 
    </li> 
</ul> 
<button data-bind="click: addPerson">Add</button>      
<input type="text" data-bind="value: cardtext" /><br /><br /><br /> 

JS

function AppViewModel() { 
    var self = this; 
    self.cardtext=ko.observable(); 


    self.people = ko.observableArray([ 
     { name: 'Bert' }, 
     { name: 'Charles' }, 
     { name: 'Denise' } 
    ]); 

    self.addPerson = function() { 
     self.people.push({ name: self.cardtext }); 
    }; 

    self.removePerson = function() { 
     self.people.remove(this); 
    } 
}  
ko.applyBindings(new AppViewModel()); 

這是結果

enter image description here

的問題是t- extbox不斷加入新的元素,但以前的新加入的元素不斷收到由新元素更新。

第三要素是3元

第四要素是4元

當我加5元的第三和得到由5個元素更新,第4單元。
爲什麼會這樣?我在做什麼錯?我不知道。

回答

1

你只需要在self.cardtext()末增加()。如果你不把括號,它會做的是將推動cardtext的可觀察對象的數組,而不是它的價值。所以,當你從文本修改cardtext,它也將修改推前一個對象。


 
function AppViewModel() { 
 
    var self = this; 
 
    self.cardtext=ko.observable(); 
 
    self.people = ko.observableArray([ 
 
    { name: 'Bert' }, 
 
    { name: 'Charles' }, 
 
    { name: 'Denise' } 
 
    ]); 
 

 
    self.addPerson = function() { 
 
    self.people.push({ name: self.cardtext() }); 
 
    }; 
 

 
    self.removePerson = function() { 
 
    self.people.remove(this); 
 
    } 
 
}  
 
ko.applyBindings(new AppViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 

 
<h4>People</h4> 
 
<ul data-bind="foreach: people"> 
 
    <li>  
 
    <span data-bind="text: name"> </span> 
 
    <a href="#" data-bind="click: $parent.removePerson">Remove</a> 
 
    </li> 
 
</ul> 
 
<button data-bind="click: addPerson">Add</button>      
 
<input type="text" data-bind="value: cardtext" /><br /><br /><br />