繁体   English   中英

在Knockout.js中的下拉更改事件中获取选定的文本

[英]Get selected text on dropdown change event in Knockout.js

我正在尝试使用敲除.js来获取下拉列表中选定索引的文本,

以下是我的HTML

<select name="" id="management" class="form-control" data-bind="value: ManagementCompanies,optionText:ManagementCompaniestxt">
<option value="0">---Select---</option>
<option value="1">abcd</option>
<option value="2">efgh</option>
</select>

以下是我的模型绑定:

var FilterViewModel = {
 ManagementCompanies: ko.observable(''),
ManagementCompaniestxt:ko.observable('')
}
FilterViewModel.ManagementCompanies.subscribe(function (newValue) {

    alert(FilterViewModel.ManagementCompaniestxt());

});
ko.applyBindings(FilterViewModel, window.document.getElementById("SelectFilters"));

我也尝试使用Text进行绑定,但是没有用。

如何在subscribe event获取选定的文本abcd

谢谢

您尝试将数据从视图获取到视图模型有点奇怪。 通常,您的视图是视图模型的表示 最好具有在模型中呈现<select>所需的数据,并使用剔除options数据绑定来呈现它。

这是您可以执行的操作:

 var FilterViewModel = { ManagementCompanies: ko.observable(''), ManagementCompaniestxt: ko.observable(''), options: [ { text: "---Select---", value: 0 }, { text: "abcd", value: 1 }, { text: "efgh", value: 2 }] } FilterViewModel.ManagementCompanies.subscribe(function(newValue) { console.log(newValue.text); }); ko.applyBindings(FilterViewModel); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <select data-bind="value: ManagementCompanies, options:options, optionsText: 'text'"> </select> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM