gpt4 book ai didi

knockout.js - knockout 未在单选按钮上设置初始真值

转载 作者:行者123 更新时间:2023-12-03 23:06:12 25 4
gpt4 key购买 nike

名称+复选框的单向绑定(bind)工作正常,但它最初不适用于单选按钮employeeTypeA,尽管它在viewmodel中的值为true,html显示单选按钮未设置,为什么会这样?

   <script type="text/javascript">

$(function()
{
var PersonViewModel = function()
{
this.firstName = ko.observable('Lisa');
this.lastName = ko.observable('T');
this.isCustomer = ko.observable(true);
this.employeeTypeA = ko.observable(true);
this.employeeTypeB = ko.observable(false);
};

var personViewModel = new PersonViewModel();
ko.applyBindings(personViewModel, $('data').get(0));
});
</script>

<div id="data">
<span data-bind="text: firstName"></span>
<span data-bind="text: lastName"></span>
<input type="checkbox" data-bind="checked: isCustomer" title="Is a customer" />
<input name="x" type="radio" data-bind="checked: employeeTypeA" title="Employee type A" />
<input name="x" type="radio" data-bind="checked: employeeTypeB" title="Employee type B" />
</div>

最佳答案

checked从文档中,单选按钮的绑定(bind)工作方式不同:

For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute.



所以你需要改变你的 PersonViewModel像这样:
var PersonViewModel = function()
{
this.firstName = ko.observable('Lisa');
this.lastName = ko.observable('T');
this.isCustomer = ko.observable(true);
this.employeeType = ko.observable('TypeB');
};

还有你的单选按钮:
<input name="x" type="radio" data-bind="checked: employeeType" 
value="TypeA" title="Employee type A" />
<input name="x" type="radio" data-bind="checked: employeeType"
value="TypeB" title="Employee type B" />

演示 JSFiddle.

如果您想保留 employeeTypeAemployeeTypeB您可以引入一个返回类型的计算属性:
this.employeeTypeA = ko.observable(false);
this.employeeTypeB = ko.observable(true);
this.employeeType = ko.computed(function()
{
if (this.employeeTypeA())
return 'TypeA';
if (this.employeeTypeB())
return 'TypeB';
},this);

同样在这种情况下,您需要添加 value单选按钮上的属性。

演示 JSFiddle.

关于knockout.js - knockout 未在单选按钮上设置初始真值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15853556/

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