knockout.js ul li数据绑定不合适

时间:2017-04-01 08:13:54

标签: asp.net-mvc knockout.js asp.net-core-mvc knockout-3.0

HTML

<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

问题是文本框不断添加新元素,但之前新添加的元素不断被新元素更新。

第3个元素是第3个元素

第4个元素是第4个元素

当我添加第5个元素时,第3个元素和第4个元素由第5个元素更新。为什么会这样?我做错了什么?我不知道。

1 个答案:

答案 0 :(得分: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 />