简体   繁体   English

选项值数据绑定不起作用

[英]Options value data-bind not working

I'm having an issue in mapping the elements of an object and binding them to an <option> element using Knockout.js. 我在映射对象的元素并将其绑定到使用Knockout.js的<option>元素时遇到问题。

The relevant section of HTML is as follows: HTML的相关部分如下:

<!-- ko if: parentObjectExists -->
<!-- ko with: parentObject -->
<div class="form-group">
 <label class="control-label" for="subTaskDistributionInput">Distribution:</label>
 <select id="subTaskDistributionInput" data-bind="options: options.distributions,  optionsText: 'value', value: key" class="form-control input-sm"></select> 
</div>
<!-- /ko -->
<!-- /ko -->    

The elements of the options.distributions array contain two elements, key and value . options.distributions数组的元素包含两个元素, keyvalue Relevant Javascript: 相关的Javascript:

function Options(data) {
  var self = this;
  self.distributions = ko.observableArray(data.Distributions);

  //Disposal
  self.isDisposed = false;
  self.dispose = function () {
      self.distributions.dispose();
      self.isDisposed = true;
  };
}

And the output options tags: 和输出选项标签:

<option value>Average</option>
<option value>Triangular</option>

A Distribution contains two elements: key , an integer, and value , a String. 分布包含两个元素: key (一个整数)和value (一个字符串)。 The value element is definitely coming through accurately into optionsText , but the key attribute is not coming through into the HTML at all. value元素肯定会准确地进入optionsText ,但是key属性根本不会进入HTML。 I'm almost certain the issue here lies in the HTML. 我几乎可以肯定,这里的问题在于HTML。 Alternative value: bindings that I've tried are 'key' , function() { return key; } 替代value:我尝试过的绑定是'key'function() { return key; } function() { return key; } , $data.key and item.key , but none of these have worked. function() { return key; }$data.keyitem.key ,但是这些都item.key If anyone can see what I'm missing here, that would be greatly appreciated. 如果有人能看到我在这里缺少的内容,将不胜感激。

You need to do it like this 你需要这样

<select id="subTaskDistributionInput" 
    data-bind="
        options: distributions,
        optionsText: $root.getValue,
        optionsValue: $root.getKey
    " 
class="form-control input-sm"></select>

Also see optionsValue instead of value 另请参阅optionsValue而不是value

Fiddle Demo 小提琴演示

See the Documentation 请参阅文档

我相信你应该写

optionsValue: 'key'

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

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