0

使用 knockoutJs 我在页面上有一个简单的选择

<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

2

Your changeCountry method should be changing the value of the underlying observable that you have bound the select to:

function changeCountry(isoId)
{
    selectedCountry(isoId);
}

That should then update both, as far as I'm aware.

You will also need to pass the new id in as a string, as knockout may well be using the type equality comparer (===), and the value in the html will be a string.

于 2013-07-15T13:35:49.423 回答
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 回答