Knockout检查绑定无法正常工作

Jus*_*son 2 javascript twitter-bootstrap knockout.js

我正在使用Twitter Bootstrap按钮组和Knockout.我觉得我忽略了一些非常简单的东西,但是,我无法checked在这种情况下获得绑定工作.

我有一个jsFiddle在这里重现问题:http: //jsfiddle.net/n5SBa/.

这是小提琴的代码:

HTML

<div class="form-group">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '0'), css: { active: Score() == '0' }">
            <input type="radio" name="score" value="0" data-bind="checked: Score" /> 0
        </label>
        <label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '1'), css: { active: Score() == '1' }">
            <input type="radio" name="score" value="1" data-bind="checked: Score" /> 1
        </label>
        <label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '2'), css: { active: Score() == '2' }">
            <input type="radio" name="score" value="2" data-bind="checked: Score" /> 2
        </label>
        <label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '3'), css: { active: Score() == '3' }">
            <input type="radio" name="score" value="3" data-bind="checked: Score" /> 3
        </label>
        <label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '4'), css: { active: Score() == '4' }">
            <input type="radio" name="score" value="4" data-bind="checked: Score" /> 4
        </label>
        <label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '5'), css: { active: Score() == '5' }">
            <input type="radio" name="score" value="5" data-bind="checked: Score" /> 5
        </label>
    </div>
</div>

<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

function SurveyViewModel() {
    var self = this;

    self.Score = ko.observable();

    //Events
    self.ClickScore = function (score) {
        self.Score(score);
    };

    //Computations
    self.RecommendationLabel = ko.computed(function () {
        if (self.Score() < 8) {
            return "Some question?";
        } else {
            return "Some other question?";
        }
    });

    self.DOMSelectedScore = ko.computed(function() {
        if ($('input[name=score]:checked').val()) {
            return $('input[name=score]:checked').val();
        } else {
            return 'no value!';   
        }
    });
};

var surveyViewModel = new SurveyViewModel();

ko.applyBindings(surveyViewModel);
Run Code Online (Sandbox Code Playgroud)

在示例中,我无法在DOM中选择实际的单选按钮,以便可以在我的表单中正确提交.

Mic*_*est 9

复选框的值是字符串("0","1"等),但您将observable的值设置为数字.该checked绑定使用全等做比较时,不考虑数量1为等于字符串"1".

您可以通过将observable的值设置为字符串来解决此问题:

data-bind="click: ClickScore.bind($data, '1')"
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/mbest/n5SBa/2/