gpt4 book ai didi

javascript - 构建 knockout 模型并动态查看,未设置单选按钮

转载 作者:行者123 更新时间:2023-11-30 17:43:53 24 4
gpt4 key购买 nike

我正在制作一个 my previous questions 完全动态,因为模型是根据服务器数据构建的, View 通过 knockout 的 ko foreach 功能循环遍历 View 模型。

我面临的问题是:

  1. 单选选项不保留值设置,即我单击操作系统,然后选择数据库选项,然后操作系统设置消失。

  2. 相关选项(在本例中为数据库和集群)在相关选项更改时未选择其初始选择(即,当操作系统更改时,数据库应返回到第一个选项,无)。

My fiddle is here 我认为问题与以下代码有关:

 computedOptions.subscribe(function () {
var section = this;
console.log("my object: %o", section);
section.selection(section.options()[0].sku);
},section);

或者我的 View 绑定(bind):

<!-- ko foreach: selectedOptions -->
<h3><span data-bind="text: description"></span></h3>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th colspan="2" style="text-align: left;">Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: options -->
<tr>
<td><input type="radio" name="$parent.name" data-bind="checkedValue: $data, checked: $parent.selection" /></td>
<td style="text-align: left;"><span data-bind="text: name"></span></td>
<td style="text-align: left;"><span data-bind="text: price"></span></td>
</tr>
<!-- /ko -->
</tbody>
</table>
<!-- /ko -->

我不确定是哪一个,希望能有一个新鲜的眼睛,因为我的大脑在 jsfiddle session 中受伤了。

最佳答案

你有两个问题:

  • 您没有正确绑定(bind)单选按钮的名称:name="$parent.name" 不是 knockout 绑定(bind)表达式,它只是分配字符串 "$parent. name" 到所有的单选按钮。您需要的是使用 attr 绑定(bind):

    <input type="radio" data-bind="checkedValue: $data, 
    checked: $parent.selection,
    attr: { name: $parent.name }" />
  • 初始选择无效,因为您正在使用 checkedValue: $data选项,这意味着您的checked 应该包含整个对象 而不仅仅是一个属性 (sku),因此您需要将 computedOptions.subscribe 更改为:

    computedOptions.subscribe(function () {
    var section = this;
    section.selection(section.options()[0]);
    },section);

演示 JSFiddle .

关于javascript - 构建 knockout 模型并动态查看,未设置单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20500414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com