【问题标题】:Populate drop-down with observable array having structures使用具有结构的可观察数组填充下拉列表
【发布时间】:2015-06-16 11:43:10
【问题描述】:

我想用下拉框切换图像。 下拉列表包含名称,并且应该向图像发送 URL。 (URL 在下拉列表中不可见)

我在文档中找到了这个例子:

<select data-bind="options: optionValues, value: selectedOptionValue">

Bot 似乎,optionValues 是 observableArray,只包含一个值,selectedOptionValue 是一个 observable,获取下拉框中选择的值。

我的 observable 数组包含结构(希望它是 JS 中的正确表达式)看起来像:

var PatternExample = function (type, name, example_url) {
            this.type = type;
            this.name = name;
            this.example_url = example_url;        
        }

名称应显示在下拉列表中,example_url 用于更改图像。

如何在选择元素中为这些数据定义数据绑定?

编辑:

在文档中也找到了答案: 示例 3:代表任意 JavaScript 对象的下拉列表,而不仅仅是字符串。

http://knockoutjs.com/documentation/options-binding.html

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    尝试在您的选择绑定中使用optionsText

    查看:

    <select data-bind="options:optionValues,optionsText:'name', value: selectedOptionValue"></select>
    
    <img data-bind="attr:{src:selectedOptionValue().url}" style="width:100px;height:100px" />
    

    视图模型:

    var ViewModel = function() {
        var self=this;
        self.selectedOptionValue=ko.observable();
        self.optionValues = ko.observableArray([{'type':'','name':'imageone','url':'www.s.com'},{'type':'','name':'imagetwo','url':'www.s1.com'},{'type':'','name':'imagethree','url':'www.s2.com'}]);
        self.selectedOptionValue.subscribe(function(data){
        console.log(data) // check the output here map url as per your requirement 
        });
    };
    
    ko.applyBindings(new ViewModel()); // This makes Knockout get to work
    

    工作样本小提琴here

    【讨论】:

    • 好的,谢谢!我现在去看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2020-11-07
    • 1970-01-01
    • 2014-08-05
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多