Knockoutjs单选按钮无法选择默认选中

时间:2016-10-21 21:56:42

标签: javascript html knockout.js

我有一个可观察的数组绑定到单选按钮,我想从中选择一个默认值。我的问题是没有明显检查单选按钮(我的意思是缺少点)。这里是一个单选按钮绑定的修改示例:

[http://jsfiddle.net/FvZXj/302/][1]

所以我设置第二个(或默认的任何选项),我需要看到该选项被选中。我错过了正确答案中的点。

请指教!

1 个答案:

答案 0 :(得分:1)

你的小提琴正在使用旧版的淘汰赛(2.0)。您可以使用3.x版本的淘汰赛中引入的checked binding。只需将checked绑定设置为$root.correctAnswer

即可
<input 
  type="radio" 
  name="uniqueQuestionName" 
  data-bind="checkedValue: $data,
    click: $root.setCorrectAnswer,
    checked: $root.correctAnswer" 
/>

演示:

function Question() {
  var self = this;
  this.name = "My Question";

  var i = 0;
  this.answers = ko.observableArray([
    new Answer(++i, "Answer 1", false),
    new Answer(++i, "Answer 2", true),
    new Answer(++i, "Answer 3", false)
  ]);

  this.setCorrectAnswer = function(correct) {
    if (correct !== self.correctAnswer()) {
      ko.utils.arrayForEach(self.answers(), function(answer) {
        answer.isRight(correct === answer);
      });

      self.correctAnswer(correct);
    }
    return true;
  };

  this.correctAnswer = ko.observable();

  this.correctAnswer.subscribe(function(newValue) {
    alert("The correct answer to " + this.name + " is now " + this.correctAnswer().name());
  }, this);
}


function Answer(id, name, isRight) {

  this.id = ko.observable(id);
  this.name = ko.observable(name);
  this.isRight = ko.observable(isRight);
}

var question = new Question();
//Set default correct answer just for example
question.correctAnswer(question.answers()[1]);
ko.applyBindings(question);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div data-bind="text:name"></div>
<div data-bind="foreach:answers">
  <label>
    <span data-bind="text: name"></span>
    <input type="radio" name="uniqueQuestionName" data-bind="checkedValue: $data,
        click: $root.setCorrectAnswer,
        checked: $root.correctAnswer" />
  </label>
  <br />
</div>

<hr/>

<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>