当从knockoutjs中的选择列表中选择项目时,值对象不会更新

时间:2013-10-07 21:07:30

标签: javascript knockout.js

我在淘汰赛的选择标签上遇到了一些问题。

我有以下标记:

<select id="faultCode" data-bind="options: FaultCodes, optionsText: 'Description', value: FaultCode, optionsCaption: 'Choose a Fault Code'"></select>
<select id="causeCode" data-bind="options: CauseCodes, optionsText: 'Description', value: CauseCode, optionsCaption: 'Choose a Cause Code'"></select>
<select id="serviceAction" data-bind="options: ActionCodes, value: ActionCode, optionsText: 'Description', optionsCaption: 'Choose an Action Code'"></select>
<select id="plantClass" data-bind="options: PlantClasses, value: PlantClass, optionsText: 'Description', optionsCaption: 'Choose a Plant Class'"></select>
<select id="plantItem" data-bind="options: PlantItems, value: PlantItem, optionsText: 'Description', optionsCaption: 'Choose a Plant Item'"></select>

我的Javascript:

self.FaultCode = ko.observable();
self.ActionCode = ko.observable();
self.PlantClass = ko.observable();
self.PlantItem = ko.observable();
self.CauseCode = ko.observable();

self.FaultCodes = ko.observableArray();
self.ActionCodes = ko.observableArray();
self.PlantClasses = ko.observableArray();
self.PlantItems = ko.observableArray();
self.CauseCodes = ko.observableArray();

self.closeRequest = function () {
    var fault = "";
    var action = "";
    var cause = "";
    var pc = "";
    var pi = "";
    if (self.FaultCode() != undefined) {
        fault = self.FaultCode();
    }
    if (self.ActionCode() != undefined) {
        action = self.ActionCode();
    }
    if (self.CauseCode() != undefined) {
        cause = self.CauseCode();
    }
    if (self.PlantClass() != undefined) {
        pc = self.PlantClass();
    }
    if (self.PlantItem() != undefined) {
        pi = self.PlantItem();
    }
}

如果用户从所有5个选择框中选择一个选项并触发closeRequest函数,则FaultCode observable的值为“”(空字符串),而CauseCode observable的值为undefined。其他三个值可观察对象都有正确的对象作为它们的值。

1 个答案:

答案 0 :(得分:0)

当您输入closeRequest或其他什么时,您确定您的FaultCode有值吗?

 console.log(self.FaultCode());

当你第一次进入这个功能时。另外,你是说(self.FaultCode() != undefined)这是一个松散的比较而不是很好。如果您从上面的console.log语句中获取了一个值,那么应该为您修复它 -

self.closeRequest = function () {
    console.log(self.FaultCode());
    var fault = "";
    var action = "";
    var cause = "";
    var pc = "";
    var pi = "";
    if (self.FaultCode()) {
        fault = self.FaultCode();
    }
    if (self.ActionCode()) {
        action = self.ActionCode();
    }
    if (self.CauseCode()) {
        cause = self.CauseCode();
    }
    if (self.PlantClass()) {
        pc = self.PlantClass();
    }
    if (self.PlantItem()) {
        pi = self.PlantItem();
    }
}

只要观察者不是falseundefined""null,它就会将错误设置为等于观察者。

当您使用双等号时,您将松散地比较该值,并使用三等于类型比较。

相关问题