gpt4 book ai didi

javascript - knockout 选项绑定(bind),嵌套选项值

转载 作者:行者123 更新时间:2023-11-30 09:58:14 25 4
gpt4 key购买 nike

假设我们的选项数组包含这样的对象

{
id: 1,
name: "Wisconsin",
attr: {
color: "red"
}
}

所以有了 knockout 绑定(bind),我们可以这样写,

<select data-bind="
options:availableStates,
optionsText:'name',
optionsValue:'id',
value:selectedStateId">
</select>

但是,如果我想要 optionsValue = attr.color,则该值为空

https://jsfiddle.net/xxhc9wwh/1/

最佳答案

我们可以使用函数代替字符串来解决这个问题。来自 Knockout 的 documentation :

Similar to optionsText, you can also pass an additional parameter called optionsValue to specify which of the objects’ properties should be used to set the value attribute on the <option> elements that KO generates. You can also specify a JavaScript function to determine this value. This function will receive the selected item as its only argument and should return a string to use for the <option> element’s value attribute.

optionsValue: function(self) { return self.attr.color }

JSFiddle demo .

关于javascript - knockout 选项绑定(bind),嵌套选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32952557/

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