【问题标题】:select option template binding to index of array选择选项模板绑定到数组的索引
【发布时间】:2011-12-08 23:57:20
【问题描述】:

我能否将选择列表的 optionsValue 绑定到 选项数组中的特定项目?

<select data-bind="options: options,  optionsText: 'text', 
optionsValue: ko.utils.arrayIndexOf(**somevalue**)" /> 

或者我是否坚持必须从

转换我的选项对象
{ 
    text: 'asdasd' 
} 

{ 
   text: 'asdasd', 
   id: 0 
} 

做事

<select data-bind="options: options,  optionsText: 'text', 
optionsValue: 'id' /> 

谢谢

【问题讨论】:

    标签: jquery knockout.js jquery-templates


    【解决方案1】:

    如果您通过 JSON 进行通信而不是提交表单,那么您可以将选定的值作为您的对象并创建一个dependentObservable 来表示它的索引,例如:

    function ViewModel() {
        this.choices = ko.observableArray([
            { text: "index zero" },
            { text: "index one" },
            { text: "index two" }
        ]);
        this.selectedChoice = ko.observable();
        this.selectedChoiceIndex = ko.dependentObservable(function() {
            return this.choices.indexOf(this.selectedChoice());
        }, this);
    };
    

    示例:http://jsfiddle.net/rniemeyer/hevTF/

    如果您正在提交表单并且依赖于所选选项元素的 value 属性,那么您可能希望将索引添加到您的对象(如您所建议的那样)。另一个选项是使用 {{each(item, index)}} 在 jQuery 模板中发出选项元素,例如:http://jsfiddle.net/rniemeyer/h6wLr/

    【讨论】:

    • 谢谢。这不是我所期望的,但它确实会起作用。
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 2013-03-23
    • 1970-01-01
    • 2019-01-05
    • 2011-12-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多