淘汰选择:按项目名称而不是值设置所选项目 [英] Knokout select : Set Selected Item by item name not value

查看:98
本文介绍了淘汰选择:按项目名称而不是值设置所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的淘汰赛选择如下

可观察阵列

issuingCountries

    0: 
       ObjectCoordinatorRegion: "EU"
       Country: "Australia"
       CountryId: 14
       Id: 1
   2: 
       ObjectCoordinatorRegion: "AU"
       Country: "Japan"
       CountryId: 16
       Id: 2

html

<select class="issuing_country" data-bind="options: issuingCountries,
                                           optionsText : 'Country',                               
                                           value:IssuingcountrySelected,
                                           optionsCaption:'---Select---',
                                         "
                        >
                        </select>

我的问题是,我手中有{国家:日本"},那么如何设置下拉菜单中选定的特定选定项目? 到目前为止,我已经尝试过

My question , i have { Country: "Japan" } in my hand,so how to set particular selected item as selected in dropdown.? so far i have tried

$('.issuing_country option[text="Japan"]').prop('selected', true); 

但是失败了,请让我知道其他方法. 谢谢

but failed ,let me know anyother way to do this. thanks

推荐答案

使用剔除功能时,您不应该尝试使用jQuery进行类似的设置-而是在viewmodel上完成所有操作.

You shouldn't be trying to set anything like that using jQuery when using knockout - instead, do it all on the viewmodel.

您的<select>选项绑定到issuingCountries observableArray,并且选定的值绑定到IssuingcountrySelected observable.要自动选择一个选项,只需在您的视图模型上设置属性,然后敲除将剩下的工作:

Your <select> options are bound to your issuingCountries observableArray, and the value selected is bound to your IssuingcountrySelected observable. To select an option automatically, just set the property on your viewmodel, and knockout will take care of the rest:

//Assuming "Japan" is at index 2:
vm.IssuingcountrySelected(vm.issuingCountries()[2]);

如果您只知道要选择的选项的名称,则首先必须找到正确的项目,因此您需要一个功能:

If all you know is the name of the option you want to select, first you must find the right item, so you'd need a function for that:

function findCountryByName(name) {
    for (var x = 0; x < vm.issuingCountries().length; x++) {
        if (vm.issuingCountries()[x].Country == name)
            return vm.issuingCountries()[x];
    }
    return null;
}
vm.IssuingcountrySelected(findCountryByName("Japan"));

这篇关于淘汰选择:按项目名称而不是值设置所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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