从淘汰下拉列表中获取文本值

Get Text Value from a Knockout Dropdown

本文关键字:取文本 获取 淘汰 下拉列表      更新时间:2023-09-26

我有各种图像类别的下拉列表:

<select class="form-control" data-bind="options: imageCategoryList, value: 'Category', optionsCaption: --Select Category--, optionsText: &#39;Category&#39;, optionsValue: 'Category', event: {change: GetImages}" id="Category" name="Category"></select>

在我的Javascript中,我试图获得下拉列表中所选内容的文本值,但我不确定如何做到

var img = self.imageCategoryList().Text

但它只返回"undefined"。如何获取所选文本值?

提前感谢!

您应该将所选选项绑定到一个可观察对象。Soo在你创建的模型:

self.selectedCategory = ko.observable();

并且在您选择的中

<select class="form-control" data-bind="options: imageCategoryList, value: selectedCategory, optionsCaption: --Select Category--, optionsText: 'Category', optionsValue: 'Category', event: {change: GetImages}"  id="Category" name="Category"></select>

在您的javascript中,您可以像一样访问它

var img = modelObject.selectedCategory();

这还没有经过测试,但这只是一个开始。

我认为这可能是您在这里想要实现的。。。

工作小提琴:http://jsfiddle.net/bPP5Q/33/

视图。。。

<select class="form-control" data-bind="
  options: imageCategoryList,
  value: selectedCategory,
  optionsCaption: '--Select Category--',
  optionsText: function(item){ return item.Category },
  event: {change: getImages}"
id="Category" name="Category"></select>

以及视图模型。。。

jQuery(function ($) {
  // this runs after the window loads
  var ViewModel = function (data) {
    var self = this;
    self.imageCategoryList = ko.observableArray([
      {
        Category: 'A',
        Text: 'CategoryA'
      },
      {
        Category: 'B',
        Text: 'CategoryB'
      },
      {
        Category: 'C',
        Text: 'CategoryC'
      }
    ]);
    self.selectedCategory = ko.observable();
    self.selectedCategory.subscribe(function(newValue) {
        console.log(newValue.Text);
    });
    self.getImages = function(){};
  }

  var vm = new ViewModel();
  ko.applyBindings(vm);
});