单击按钮时,Observable不起作用

时间:2016-02-10 18:22:00

标签: jquery knockout.js

我有一个json与" id"元素,我正在传递" id"在文本框中,想要在按钮单击下找到下面列表中相应项目的更改颜色。

Js代码:

   var bugTracker=function(){
    var self=this;
    self.bugId=ko.observable(),
    self.bugList=ko.observableArray([
    {id:1,name:"Abc"},{id:2,name:"Dooo"},{id:3,name:"Usss"},{id:4,name:"Yeess"}
    ])
    self.currentSelectedId=ko.observable(0);

    self.getSelected=function(data){
    console.log(self.bugId());
    this.currentSelectedId(self.bugId());
    console.log(this.currentSelectedId());
    }

    self.getClicked=function(data){
    //console.log(self.bugName());
    this.currentSelectedId(data.id);
    console.log(this.currentSelectedId());
    }

   }

   $(function(){
   ko.applyBindings(new bugTracker());
   });

HTML code:

<div class="content">
    <label>Enter Bug Id:</label>
    <input type="text" data-bind="value : bugId" >
    <input type="button" data-bind="click: getSelected" value="Select Item"/>
    <ol data-bind="foreach : bugList">
        <li data-bind="text : name,css:{'filteredItemTex': id===$parent.currentSelectedId()},'click': function(){$parent.getClicked($data);}" >
        </li>
    </ol>

</div>

Css:

.filteredItemTex{
        color:red;
        }

1 个答案:

答案 0 :(得分:0)

问题是bugId绑定到文本框,因此其值为字符串。 id === $parent.currentSelectedId()失败,因为===正在进行严格的比较。

您可以将其更改为==,或使用parseInt

self.getSelected = function(data) {
    console.log(self.bugId());
    this.currentSelectedId(parseInt(self.bugId()));
    console.log(this.currentSelectedId());
}

小提琴:https://jsfiddle.net/79gto4qx/