3

値を持つオプションを使用して 2 つの選択フィールドをアクティブにしようとしています。<option value='...'>...</option>Knockoutjs を使用します。

そして、最初の選択フィールドで選択した値に基づいて、2 番目の選択フィールド オプションに値を設定します。

参考までに、 http://knockoutjs.com/examples/cartEditor.htmlを見つけましたが、これも optionsValue を使用しないため、役に立ちませんでした。

これが私の見解です:

<select data-bind="options: list,
                   optionsCaption: 'Select...',
                   optionsText: 'location',
                   optionsValue: 'code',
                   value: selectedRegion">                 
</select>
<!-- ko with : selectedRegion -->
<select data-bind="options: countries,
                   optionsCaption: 'Select...',
                   optionsText: 'location',
                   optionsValue: 'code',
                   value: $parent.selectedCountry">
</select>
<!-- /ko  -->

これが私の見解です:

var packageData = [
    {
        code : "EU",
        location: 'Euprope',
        countries : [
            { location: "England", code: 'EN' },
            { location: "France", code: 'FR' }
        ]
    },
    {
        code : "AS",
        location: 'Asia',
        countries : [
            { location: "Korea", code: 'KO' },
            { location: "Japan", code: 'JP' },
        ]
    }
];

function viewModel(list, addons) {
    this.list = list;
    this.selectedRegion = ko.observable();
    this.selectedCountry = ko.observable();
}

ko.applyBindings(new viewModel(packageData)); 

上記を実行すると、次の JS エラーが発生します。

Uncaught ReferenceError: Unable to parse bindings.
Bindings value: options: countries,
                   optionsCaption: 'Select...',
                   optionsText: 'location',
                   optionsValue: 'code',
                   value: $parent.selectedCountry
Message: countries is not defined

ビューで 'optionsValue: 'code,' 行 (最初の選択フィールド用に 1 つ、2 番目の選択フィールド用に 1 つ) を失った場合、上記は機能しますが、これはオプション値を入力せず、これは私が望むものではありません。

たとえば、<option value>...</option>代わりに<option value="[country code]">...</option>.

コードを修正する方法を教えてください<option value="[country code]">...<option>

よろしくお願いします。

4

1 に答える 1

5

問題は、optionsValueプロパティを設定するselectedRegionと、コードのみが入力されるようになることです。code プロパティの下にcountries プロパティがないため、バインディングは失敗します。これを回避する 1 つの方法は、selectedRegionコードに基づいて国を返す計算されたオブザーバブルを使用することです。

self.countryList = ko.computed(function () {
    var region = self.selectedRegion();
    var filtered = ko.utils.arrayFirst(self.list, function (item) {
        return item.code == region;
    });
    if (!filtered) {
        return []
    } else {
        return filtered.countries;
    }
});

次に、バインディングを変更して、computed: を使用するだけですoptions: $root.countryList

作業例: http://jsfiddle.net/infiniteloops/AF2ct/

于 2013-11-10T04:45:56.040 に答える