0

我是 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/

4

2 回答 2

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());
于 2013-09-12T23:19:56.887 回答
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>

见小提琴

我希望它有所帮助。

于 2013-09-13T07:18:15.190 回答