【问题标题】:KO radio works but does not initialise as checkedKO 收音机工作但未按检查初始化
【发布时间】:2017-03-23 12:26:39
【问题描述】:

这是来自基于淘汰赛的答案编辑器的 sn-p

<!-- ko foreach: Answers -->
<div class="qa-box" data-bindx="event: { mousedown: mouseDown, dragend: dragEnd, dragstart: dragStart }">
  <div class="qa-body">
    <div class="radio">
      <label>
        <input type="radio" data-bind="attr: { name: 'Q' + $parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer" /><span></span>
        Tick the correct answer
        <span data-bind="text:$parent.CorrectAnswer"></span>
      </label>
      <a href="#" data-bind="click: $parent.remove.bind($parent)">
        <i class="fa fa-times"></i>
        Remove this answer
      </a>
      <div class="form-control" contenteditable="true" data-bind="ckeditor: $data, attr: { id: 'Q' + $parentContext.$index() + 'A' + $index() }"></div>
    </div>
  </div>
</div>
<!-- /ko -->
<div>CorrectAnswer: <span data-bind="text: CorrectAnswer"></span></div>

您会注意到我在单选按钮标签的末尾放置了一个绑定跨度,这样当我与 UI 交互时,我可以看到 CorrectAnswer 可观察对象发生了什么。这就是我知道它正确绑定到视图模型的方式。单击单选按钮或其标签会完全按照预期更改 CorrectAnswer 的值。

这也让我知道 CorrectAnswer 包含我预期的值。

让我们仔细看看绑定,以防它不明显。

attr: { name: 'Q'+$parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer

给定问题的所有答案都具有相同的名称 Qx 和由项目的列表位置提供的值。当一个项目被点击时,它的列表位置被写入CorrectAnswer。这确实发生了,作为证据 div 中显示的新值。

那么,在其他一切正常的情况下,什么会阻止 UI 初始化为已检查?

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    这不是初始化问题,而是类型兼容性问题。单选输入的值是字符串类型。我的视图模型提供的值是数字类型。 Knockout 进行了强比较,但无法识别匹配项。

    另见Radio buttons Knockoutjs

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 2021-09-21
      • 2016-05-29
      • 2022-08-02
      • 2013-11-30
      • 2010-12-20
      • 1970-01-01
      • 2021-05-24
      • 2021-03-20
      相关资源
      最近更新 更多