KnockoutJS 选择选项和选定值 [英] KnockoutJS Select Options and Selected Value

查看:15
本文介绍了KnockoutJS 选择选项和选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似问题:选择元素的初始值

我在设置 select 元素的初始值时遇到问题.我基本上有一个来自服务器的种子数据列表来填充下拉列表,我希望选定的值代表应该从实体中选择的内容.

I'm having an issue setting the initial value of the select element. I basically have a list of seed data coming in from the server to populate the drop down list, and I want the selected value to represent what should be selected from the entity.

因为数据模型的选择值不等于种子数据中的对象引用,所以没有选择任何东西.

Because the data model's selected value doesn't equal the object reference in the seed data, nothing is selected.

现在,我正在遍历每个实体,找到正确的选定值,将其设置为等于种子数据的等效值,然后 Knockout 知道如何将其连接起来.

Right now, I'm looping through each entity, finding the correct selected value, setting that equal to the seed data's equivalent, then Knockout knows how to wire it up.

有没有比这更优雅的解决方案?我用更多细节摆弄了一个简化的例子...... http://jsfiddle.net/hbrYM/14/

Is there a more elegant solution that this? I fiddled a simplified example with more details... http://jsfiddle.net/hbrYM/14/

推荐答案

正如您正确猜测的, selectedValue 引用不匹配,因此 KO 不会选择该项目.实现这一点的方法是不要将复杂对象保存在选定的值中,而是选择 ID,因为原始类型相等可以成功并选择正确的值.

As you correctly guessed the selectedValue reference doesn't match so KO doesn't select that item. The way to get this to work is to not save the complex object in the selected value and instead select the ID, as a primitive type equality can succeed and the correct value is selected.

http://jsfiddle.net/VLTFB/3/

您需要在选项绑定上使用 optionsValue 选项(如果有意义:)

You'll need to use the optionsValue option on the options binding (if that makes sense :)

<select data-bind="options: seedData,
                    optionsText: 'firstName',
                    optionsValue: 'ID',
                    value: data.selectedValue">

编辑

如前所述,您可以使用计算(未经测试)重新选择正确的项目.

As discussed you can reselect the correct item with a computed (untested).

vm.currentlySelected = ko.computed(function () { 
   for (var i = 0; i < this.seedData().length; i += 1) {
       var data = this.seedData()[i];
       if (data.ID === this.selectedValue()) {
           return data;
       }
   }
   return null;
}, vm);

希望这会有所帮助.

这篇关于KnockoutJS 选择选项和选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆