假设我们的选项数组包含这样的对象
{
id: 1,
name: "Wisconsin",
attr: {
color: "red"
}
}
所以有了 knockout 绑定(bind),我们可以这样写,
<select data-bind="
options:availableStates,
optionsText:'name',
optionsValue:'id',
value:selectedStateId">
</select>
但是,如果我想要 optionsValue = attr.color
,则该值为空
最佳答案
我们可以使用函数代替字符串来解决这个问题。来自 Knockout 的 documentation :
Similar to
optionsText
, you can also pass an additional parameter calledoptionsValue
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 }
关于javascript - knockout 选项绑定(bind),嵌套选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32952557/