我正在尝试使用 knockout 创建一组下拉菜单,允许用户从列表中选择最多 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 个可观测值必须基于初始数据,并排除其他三个下拉列表中的选定数据。我真的很挣扎。我什至无法实现它。
这是否可能或者是否适合 Knockout 或者我应该只用 onChange 来查看 JS
最佳答案
这在 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>
我正在使用我的 repeat绑定(bind)插件来创建重复的选择元素,但如果您愿意,您可以使用其他方法。
关于javascript - 如何创建共享单个列表的链接下拉列表并确保只能在一个下拉列表中选择每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11092291/