Knockout.js:使用单选按钮切换Dom元素的可见性

时间:2013-09-12 23:03:26

标签: knockout.js

我是KO的新手并且一步一步地学习。

我想根据所选的单选按钮值切换DOM可见性。我的代码没有按预期工作,请帮助....

HTML

<div>
    Wanna see what is next? 
    <p><label><input type="radio" name="MyChoice" value="True" data-bind="checked: MyChoiceValue" /> Yes</label>
        <label><input type="radio" name="MyChoice" value="False" data-bind="checked: MyChoiceValue" /> No</label></p>
</div>

<div data-bind="visible: isVisible">
    <h1>Hello World !</h1>
</div>

和我的 Javascript

viewModel = function() {
     var self = this;   
     self.isVisible: ko.observable(''),
     self.MyChoiceValue: function() {
         if(self.MyChoiceValue() === 'True') {
                 self.isVisible(true);
         } else {
                 self.isVisible(false);
         }
     }   
};
ko.applyBindings(new viewModel);

的jsfiddle

http://jsfiddle.net/gbhasha/tCQtp/5/

2 个答案:

答案 0 :(得分:1)

在这里查看http://jsfiddle.net/tCQtp/6/

<div>
    Wanna see what is next? 
    <p><label><input type="radio" name="MyChoice" value="true" data-bind="checked:MyChoice.ForEditing" /> Yes</label>
        <label><input type="radio" name="MyChoice" value="false" data-bind="checked:MyChoice.ForEditing" /> No</label></p>
</div>

<div data-bind="visible: MyChoice">
    <h1>Hello World !</h1>
</div>
<div data-bind="text: ko.toJSON($root)"></div>

var ViewModel = function() {
   this.MyChoice = ko.observable(true);

   this.MyChoice.ForEditing = ko.computed({
        read: function() {
            return this.MyChoice().toString();  
        },
        write: function(newValue) {
             this.MyChoice(newValue === "true");
        },
        owner: this        
    });          
};
ko.applyBindings(new ViewModel());

答案 1 :(得分:0)

您可以将单选按钮绑定到可观察对象。并在视图中测试此observable的值。

var ViewModel = function() {
     var self = this;     
     self.MyChoiceValue= ko.observable();     
};

ko.applyBindings(new ViewModel());

观点:

<div>
    Wanna see what is next? 
    <p><label><input type="radio" name="MyChoice" value="True" data-bind="checked: MyChoiceValue" /> Yes</label>
        <label><input type="radio" name="MyChoice" value="False" data-bind="checked: MyChoiceValue" /> No</label></p>
</div>

<div data-bind="visible: MyChoiceValue() == 'True'">
    <h1>Hello World !</h1>
</div>

See fiddle

我希望它有所帮助。