这是基于 knockout 的答案编辑器的片段
<!-- 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>
您会注意到,我在单选按钮标签的末尾放置了一个绑定(bind)范围,这样我就可以看到当我与 UI 交互时 CorrectAnswer
可观察对象发生了什么。这就是我知道它正确绑定(bind)到 View 模型的方式。单击单选按钮或其标签会完全按照预期更改 CorrectAnswer
的值。
这也让我知道 CorrectAnswer 包含我期望的值。
让我们仔细看看绑定(bind),以防它不明显。
attr: { name: 'Q'+$parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer
给定问题的所有答案都具有相同的名称 Qx 和由项目的列表位置提供的值。单击某个项目时,其列表位置将写入 CorrectAnswer
。这确实发生了,作为证据的新值出现在泄露 div 中。
那么,当其他一切都正常时,什么可能会阻止 UI 初始化(如检查所示)?
最佳答案
这不是初始化问题,而是类型兼容性问题。 radio 输入的值是字符串类型。我的 View 模型提供的值是数字类型。 Knockout 进行了强比较,但无法识别匹配项。
关于javascript - KO radio 可以工作,但未按照检查进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967071/