gpt4 book ai didi

knockout.js - 用于检查的 knockoutjs radio 整数数据绑定(bind)不起作用

转载 作者:行者123 更新时间:2023-12-04 17:09:49 25 4
gpt4 key购买 nike

查看JSFiddle

<div data-bind="foreach: ids" class="">
<label>
<input type="radio" name="someid" data-bind="value: value, checked: $root.selectedid" />
<span data-bind="text: text"></span>
</label>
</div>
<br/>
<input type="button" data-bind="click: test1" value="Test1"/>
<input type="button" data-bind="click: test2" value="Test2"/>
<input type="button" data-bind="click: test3" value="Test3"/>

功能 radio 数据(文本,值){
this.text = 文本;
this.value=值;
}
var viewModel = function(){
var self = this;
self.selectedid = ko.observable();

self.ids = ko.observableArray([
new radiodata('one',1),
new radiodata('two',2),
new radiodata('three',3)
]);
self.test1 = function(){
self.selectedid(2);//this doesnot work
};
self.test2 = function(){
self.selectedid('2');//this works
};
self.test3 = function(){
self.selectedid((3).toString());//this was my hack
};
}

var model = new viewModel();
ko.applyBindings(model);

我试图 radio databind对于 checked属性(property),
我的 selectedid 的 json 数据是我试图绑定(bind)的整数 checked对于 radio 。

我也为此修补了解决方案,但是有人知道为什么整数数据绑定(bind)不起作用吗?

像,在哪里 self.testX功能将改变 radio checked属性(property)
self.test1 = function(){
self.selectedid(2); //this doesnot work
};
self.test2 = function(){
self.selectedid('2');//this works
};
self.test3 = function(){
self.selectedid((3).toString()); //and this was my hack
};

有什么好的解释吗?

最佳答案

您还需要使用 checkedValue如果你想要 checked 绑定(bind)绑定(bind)以使用元素的值字符串以外的其他内容进行选择。来自 the knockout documentation on the checked binding :

If your binding also includes checkedValue, this defines the value used by the checked binding instead of the element’s value attribute. This is useful if you want the value to be something other than a string (such as an integer or object), or you want the value set dynamically.



如果您查看文档,您还会看到他们使用当前 $data 的示例。对象为 checkedValue .

编辑:添加解释为什么将值转换为字符串有助于解决问题。

如果将整数转换为字符串,选择工作正常的原因是检查的绑定(bind)在不允许类型转换的情况下进行相等性比较,即使用 ===而不是 ==用于平等比较。

这方面的一个例子是:
1 == "1" // true
1 === "1" // false

在上面示例的第一行中,JavaScript 在执行比较时进行了类型转换(这使得比较运算符两侧的操作数具有相同的类型),而在后者中则没有。

关于knockout.js - 用于检查的 knockoutjs radio 整数数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21777963/

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