除了我的 MVC3 项目,我们设计了一个页面,分别包含 3 个安全问题和答案(下拉列表中大约 10 个)。可以从下拉列表中选择问题,答案将填写在其下方的文本框中。
设计:假设用户选择 question1 作为(10 个问题中的 1 个)。第二个下拉菜单应该只显示 9 个问题(跳过第一个问题)。以同样的方式,第三个问题将只有 8 个选项。
同样,如果用户将索引更改为 0(表示选择问题)。他删除的那个问题应该出现在其他下拉列表中。
请帮助设计此页面。我尝试使用 JQuery,但这并没有帮助我。
除了我的 MVC3 项目,我们设计了一个页面,分别包含 3 个安全问题和答案(下拉列表中大约 10 个)。可以从下拉列表中选择问题,答案将填写在其下方的文本框中。
设计:假设用户选择 question1 作为(10 个问题中的 1 个)。第二个下拉菜单应该只显示 9 个问题(跳过第一个问题)。以同样的方式,第三个问题将只有 8 个选项。
同样,如果用户将索引更改为 0(表示选择问题)。他删除的那个问题应该出现在其他下拉列表中。
请帮助设计此页面。我尝试使用 JQuery,但这并没有帮助我。
试试这个代码
$(function() {
// Load all the dropdowns
$('[id^=select]').html($('.template').html());
// This array Holds the Objects
var arr = ['select1', 'select2', 'select3'];
// Declare a array where you store the selections
var arrSelect = {
'select1': '0',
'select2': '0',
'select3': '0'
};
$('select').on('change', function() {
var currID = $(this).prop('id');
// Set the Current selection
arrSelect[currID] = $(this).val();
// Iterate Thru each dropdown
$.each(arr, function(i) {
var temp = arrSelect[arr[i]];
// Clone the template
var $clone = $('.template').clone();
// Remove Questions from template based on selected
// values in other select's
$.each(arrSelect, function(index, value) {
if (value != 0 && value != temp) {
$clone.find('option[value=' + value + ']').remove();
}
});
// If not Current select rewrite its
// contents of the select
if (arr[i] != currID) {
//console.log('#' + arr[i] + ' :: ' + $clone.html());
$('#' + arr[i]).html('').html($clone.html());
$('#' + arr[i]).val(temp);
}
});
});
})
我会使用Knockout。基本上创建一个返回可用问题的 JavaScript Viewmodel。
我有类似的要求,以下工作。
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>