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

标签 javascript knockout.js

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

{
    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/

相关文章:

javascript - 如何获得一个什么都不做的链接

javascript - BrowserSync 阻止在 Firefox (OS X) 中导航

jquery - 当数据属性更新时Knockout Js更新ViewModel

javascript - 在某些情况下, knockout 模板仍处于加载状态

javascript - Knockoutjs 函数更新模型时出现预期异常

javascript - knockout JS : indexOf always returns -1?

javascript - 如何根据SectionList中的键填充ui上数组的值

javascript - MVC4 局部 View 中的 knockout 绑定(bind)

javascript - 无法解析 babel-runtime/regenerator

jquery - Knockout.js 与 jQuery 表排序器