javascript 淘汰赛可见绑定不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13570540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:10:38  来源:igfitidea点击:

Knockout visible binding not working

javascriptknockout.js

提问by Alex

I've got a very simple View Model:

我有一个非常简单的视图模型:

var ViewModel = function() {
    this.showRow = ko.observable(false);
    this.toggleVisibility = function() {
        if(this.showRow == true){
            this.showRow = false;
        }
        else{
            this.showRow = true;
        }
        alert('showRow is now '+this.showRow); //only here for testing
    };
};

with equally simple markup:

使用同样简单的标记:

<a href="#" data-bind="click: toggleVisibility">Toggle</a>
<br />
<table>
    <tr data-bind="visible: showRow">Some Text</tr>
</table>

My problem is, that when the link is clicked, the alert box shows (displaying the correct value - true/false)

我的问题是,当点击链接时,警报框显示(显示正确的值 - 真/假)

However, the visible binding on the trelement doesn't seem to work - either initially (the row should be invisible on load) nor when the value of showRowtoggles.

但是,tr元素上的可见绑定似乎不起作用 - 无论是最初(该行在加载时应该是不可见的)还是在showRow切换值时。

jsFiddle of above- http://jsfiddle.net/alexjamesbrown/FgVxY/3/

上面的 jsFiddle- http://jsfiddle.net/alexjamesbrown/FgVxY/3/

采纳答案by photo_tom

You need to modify your html as follows:

您需要按如下方式修改您的 html:

<table>
    <tr data-bind="visible: showRow"><td>Some Text</td></tr>
</table>

And JavaScript as follows:

和 JavaScript 如下:

var ViewModel = function() {
    var self = this;
    self.showRow = ko.observable(false);
    self.toggleVisibility = function() {

        self.showRow(!self.showRow());
        alert('showRow is now ' + self.showRow());
    };
};

ko.applyBindings(new ViewModel());

Syntax to set the value to observable property is: self.showRow(value);

将值设置为可观察属性的语法是: self.showRow(value);

If need to have tags inside of tags.

如果需要在标签内有标签。

I've also modified your fiddle to simplify the javascript and follow newer code practices with regard to "this". See http://jsfiddle.net/FgVxY/4/

我还修改了您的小提琴以简化 javascript 并遵循有关“this”的较新代码实践。见http://jsfiddle.net/FgVxY/4/