0

ノックアウトJsを使用して、ページで簡単に選択できます

<select id="voucherCountry" data-bind="options: availableCountries, optionsValue:'isoId', optionsText: 'country', value:selectedCountry"></select> 

私が持っているビューモデルで

function searchViewModel()
{
    var self = this;
    self.voucherNumber = ko.observable();
    self.selectedCountry = ko.observable();
    self.availableCountries = ko.observableArray(
        [
            new Country(250, 'France'),
            new Country(276, 'Germany'),
            new Country(724, 'Spain'),
            new Country(380, 'Italy'),
            new Country(826, 'United Kingdom')
        ])

function Country(iso, name)
{
    this.isoId = iso;
    this.country = name;
}

HTML ページで、ドロップダウンの値を変更し、ドロップダウン リストに新しいオプションを表示して、ビュー モデルで selectedCountry を更新できるようにしたいと考えています。

だから私は簡単なjQueryステートメントを試しました

function changeCountry(isoId)
{
    $(voucherCountry).val(isoId);
}

そのように呼ばれています

changeCountry(380);

これを呼び出すと、ドロップダウンのテキストは変更されませんが、クリックしてオプションを変更すると、変更したいオプションが強調表示されます。

selectedCountry() 変数を助けているものを表示すると、変更されたものではなく、初期値に設定されます。

したがって、ビューモデルではなくUIを更新しているようです。

これには簡単な解決策があるはずだと確信していますが、私はそれを得ていません

アップデート:

さて、これでボタンができました

<button type="button" data-theme="b" data-bind="click: scanBarcode">Scan Barcode</button>

ビューモデルでは、この関数:

self.scanBarcode = function()
{
    self.selectedCountry(380);
}

selectedCountry は更新されていますが、UI は更新されていません。

<select>データバインドで optionsValue および value 属性を使用する方法に問題があると思いますか?

4

2 に答える 2

1

This block

function changeCountry(isoId)
{
    $(voucherCountry).val(isoId);
}

Has multiple possible issues.

First, $(voucherCountry) probably doesn't evaluate to a valid selector; if you want to select the dropdown by id you'll need to do this: $("#voucherCountry").

Then you can use $("#voucherCountry").val(123).

The second thing that could be mixing things up is that you're modifying the UI as a way of indirectly modifying your viewmodel - you're probably better off updating your VM directly, as in searchViewModel.selectedCountry(123)

于 2013-07-15T13:36:20.280 に答える