【问题标题】:Knockout access selected value in select剔除访问选择中的选定值
【发布时间】:2019-01-01 16:07:09
【问题描述】:

如何获取选择的选定值?

HTML:

<select data-bind="options: customers, optionsText: 'customer_display_name', optionsValue: 'customer_id'"></select>

Javascript:

var customers = <?php echo json_encode($this->customers); ?>;
self.customers = ko.mapping.fromJS(customers);

如何在我的 ViewModel 中访问当前选择的“optionsText”或“optionsValue”?

self.customers...?

【问题讨论】:

  • 您的绑定表明该值已绑定到customer_id,因此您可以使用它。

标签: knockout.js knockout-mapping-plugin knockout-3.0


【解决方案1】:

你可以这样做:

function ViewModel() {
  this.selectedCustomer = ko.observable();
  this.customers = [{
    customer_display_name: "Bob",
    customer_id: 10 
  }, {
    customer_display_name: "Joseph",
    customer_id: 20 
  },{
    customer_display_name: "Charlie",
    customer_id: 30 
  }];
  
  // Only for debug purposes
  this.selectedCustomer.subscribe(function (newValue) {
    console.info(newValue);
  }, this);
}
ko.applyBindings(new ViewModel());  
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: customers, optionsText: 'customer_display_name', optionsValue: 'customer_id', value: selectedCustomer"></select>

一个可观察的 selectedCustomer 持有当前选定客户的“customer_id”属性值。如果您希望 selectedCustomer 保存当前选定客户的整个对象,只需从您的 HTML 代码中删除一个属性“optionsValue: 'customer_id'”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2014-07-08
    相关资源
    最近更新 更多