如果在knockoutjs中绑定不起作用

时间:2016-02-22 00:40:23

标签: javascript html knockout.js data-binding

我试图在knockoutjs中使用带有数据绑定的if语句:

例如,if if应该为false并且div中的文本应该隐藏:

    <!-- this is what i am trying to get working. -->
    <div data-bind="if: little">rank : little</div>

我的猜测是这件作品没有按预期工作。它应该返回false,因为在启动时clickCount为0。

  this.little = function(){
    return this.clickCount() > 5;
  };

我已经粘贴了app.js和index.html的代码。

这是app.js

var ViewModel = function (){
  this.clickCount = ko.observable(0);
  this.name = ko.observable('Tabby');
  this.imgSrc = ko.observable('img/2.jpg');
  this.imgAttribution = ko.observable('http://www.flickr.com/photos/big');


  this.incrementCounter = function() {
    this.clickCount(this.clickCount() + 1);
  };


  // this is not returning false as it should.
  this.little = function(){
    return this.clickCount() > 5;
  };

}

ko.applyBindings(new ViewModel());

这是index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cat Clicker</title>
</head>
<body>

    <div>

        <h2 data-bind="text: name"></h2>
        <div data-bind="text: clickCount"></div>

        <!-- this is what i am trying to get working. -->
        <div data-bind="if: little">rank : little</div>

        <img src="" alt="cute cat" data-bind="click: incrementCounter, attr:{src: imgSrc}">

    </div>
    <script src="js/lib/knockout-3.2.0.js"></script>
    <script src="js/app.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您好,您可以使用敲除的可见绑定

以下代码适合您:

    <div data-bind="visible: !little()">rank : little</div>
                            OR
    <div data-bind="visible: little()">rank : little</div>