2

我正在尝试使用淘汰赛创建一组下拉列表,允许用户从列表中选择最多 3 个值,例如颜色。列表开头为:- 红色、橙色、黄色、绿色、蓝色、靛蓝色、紫色

DropDown 1 - Select any of the 7
DropDown 2 - Select any of the 6 remaining
Dropdown 3 - Select any of the 5 remaining

如果用户返回并将 DropDown 1 更改为某种颜色,他们应该只能选择其他剩余颜色(以及 Drop Down 1 中的颜色)。如果他们随后更改它,我将能够转到下拉列表 2 或 3 并将其更改为以前在 1 中的值。

我想我需要一个包含 7 个项目的初始数组,然后我需要一个可观察的每个下拉列表。3 个 observables 必须基于初始数据并排除其他三个下拉列表中的选择。我真的很挣扎。我什至无法实现它。

这是否可能或是否适合用于 Knockout 或者我应该只使用 onChange 来查看 JS

4

1 回答 1

2

这在 Knockout 中绝对是可能的。可能有 10 种方法可以做到这一点。我在这里想出了一种方法:

http://jsfiddle.net/mbest/wfW97/

这是供参考的代码:

function ViewModel() {
    var self = this;
    self.colors = ['red','orange','yellow','green','blue','indigo','violet'];
    self.selections = [];
    ko.utils.arrayForEach(self.colors, function() {
        self.selections.push(ko.observable());
    });
    self.selfAndUnselectedColors = function(index) {
        var selfColor = self.selections[index]();
        return ko.utils.arrayFilter(self.colors, function(color) {
            return color === selfColor || !ko.utils.arrayFirst(self.selections, function(sel) {
                return color === sel();
            });
        });
    }
}
ko.applyBindings(new ViewModel());

和 HTML:

<div data-bind="repeat: colors.length">
    <select data-bind="options: selfAndUnselectedColors($index), optionsCaption: 'select a color', value: selections[$index]"></select>
</div>​

我正在使用我的重复绑定插件来创建重复的选择元素,但如果你愿意,你可以使用其他方法。

于 2012-06-20T02:16:52.867 回答