简体   繁体   English

Knockout.js-未设置选择值

[英]Knockout.js - select value not set

I am using knockout.js, and it's not setting the value of an empty option (Four): 我正在使用淘汰表.js,并且没有设置空选项(四个)的值:

<select data-bind="value: item.widgetValue, attr: {id: item.widgetName, name: item.widgetName}, options: item.options, optionsText: ‘label’, optionsValue: ‘value’” id=”fld-“ name=”fld0”>
  <option value=”one”>One</option>
  <option value=”two”>Two</option>
  <option value=”three”>Three</option>
  <option value>Four</option>
  ...
</select>

This is creating a problem: when you're on any option and try to select Four, it selects One; 这就产生了一个问题:当您选择任何选项并尝试选择“四”时,它会选择“一个”; it will only select Four the second time you try to select it. 它将在您第二次选择它时仅选择4。

I have tried changing the knockout data-bind to fix it: 我尝试过修改敲除数据绑定来解决此问题:

value: $.trim(item.widgetValue)

This allows you to select Four immediately, but incorrectly shows One as being selected after you submit the form with Four selected. 这使您可以立即选择“四”,但是在提交“四”后提交表单后,会错误地显示“一”。

Any ideas as to what could be causing this, or how to fix it? 关于什么可能导致此问题或如何解决的任何想法?

You shouldn't be manually setting options if you are using the options binding on your select element. 如果在select元素上使用选项绑定,则不应手动设置选项。 If those are being dynamically created by the binding (ie. you are actually using item.options for your source) then check the objects you are binding the select element to - 如果这些是通过绑定动态创建的(即您实际上是在使用source.options作为源),则检查将select元素绑定到的对象-

item.options probably looks like this (missing a value or is somehow not like the other options) - item.options可能看起来像这样(缺少值或不像其他选项那样)-

item.options = [
    { label: 'someLabel1', value: 'someValue1' },
    { label: 'someLabel2', value: 'someValue2' },
    { label: 'someLabel3', 'someValue3' }
    ];

but should be a more uniform object like this (well defined model) - 但应该是更统一的对象,例如这样(定义明确的模型)-

function optionModel(label, value) {
    var self = this;
    self.label = ko.observable(label);
    self.value = ko.observable(value);
}

item.options = [
    new optionModel('someLabel1', 'someValue1'),
    new optionModel('someLabel2', 'someValue2'),
    new optionModel('someLabel3', 'someValue3')
    ];

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

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