【问题标题】:binding both optionValue and optionText in a select box from arbitrary JavaScript objects在任意 JavaScript 对象的选择框中绑定 optionValue 和 optionText
【发布时间】:2012-04-26 06:12:10
【问题描述】:

我可以绑定optionsText,但不能绑定optionsValue。两个函数应该相同吗?

渲染的 html:(值在哪里?)

<option value="">ROSSFORD D</option>

查看:

  <select multiple="multiple" width="75" id="foo" name="campaign[precincts][]" data-bind="options: campaign_precincts, optionsText: function(item) { 
                       return item.precinct_location.id 
                   }, optionsValue: function(foo) {return foo.precinct_location.id }> </select>

查看模型:

 var newCampaign = function() {
    this.items = ko.observableArray();
    this.freeText = ko.observable("");
    this.campaign_precincts = ko.observableArray();
    this.selectedPct = ko.observable();
    this.campaignName = ko.observable();
    this.userParty = ko.observable("");

    self = this;
    var question = this.freeText();

    this.searchMe = function() {
    console.log (self.userParty());
    self.items([]);
    self.userParty()
        if (this.freeText() != "") {
         // search by city
         $.getJSON('/search.json?q=' + this.freeText(), function (data) {
            if (data) {
              console.log(data)
              data.forEach(function(item) { self.items.push(item) })
            }
          });
        // search by zipcode
        $.getJSON('/search.json?z=' + this.freeText(), function (data) {
            if (data) {
              data.forEach(function(item) { self.items.push(item) })
            }
          });
        }
    }.bind(this); 

    this.addPrecinct = function(pct) {
      // returs false if pct is not a member of the array
      x = function(a,b){return!!~a.indexOf(b)}
      if ( x(self.campaign_precincts(),pct) == false) {
        self.campaign_precincts.push(pct);
      }; 
    }.bind(this);

    this.removePct = function() {
      self.campaign_precincts.pop(self.selectedPct());
    }
};

ko.applyBindings(new newCampaign());

js 对象:

data.precinct_location.city => "string"
data.precinct_location.id => 1234

【问题讨论】:

    标签: javascript binding knockout.js html-select


    【解决方案1】:

    KO 代码目前不考虑是否将 a 函数传递给 optionsValue。有一个问题,在这里谈论为绑定选项添加更全面和灵活的选项:https://github.com/SteveSanderson/knockout/pull/154

    现在,您确实需要映射数据(即使只是在客户端),以便可以直接从数组项上的属性读取值。如果您在这方面需要任何帮助,我很乐意提供帮助。

    【讨论】:

      猜你喜欢
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 2019-07-08
      • 2018-06-02
      • 2017-01-11
      相关资源
      最近更新 更多