这是我在 actionscript 中遇到的问题,但同样适用于 Javascript 或 Jquery。基本上,我有 3 个选择框,例如:
<select id="color">
<option>Red</option>
<option>Blue</option>
<option>Green</option>
</select>
<select id="size">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="type">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
选择颜色时 - 我希望尺寸和类型仅过滤掉适用于该颜色的尺寸和类型。此外,当用户随后选择尺寸时,类型应该进一步减少,并且颜色也应该根据尺寸过滤。
我已经为这个问题苦苦挣扎了一段时间,但还没有找到一个优雅的解决方案。有人有任何方法的线索吗?
最佳答案
// Assuming this is some kind of store, with items with different capabilities.
var data = [{id:"item1", color:"red", size:1, type:"A"},
{id:"item2", color:"red", size:2, type:"B"},
{id:"item3", color:"blue", size:3, type:"C"},
{id:"item4", color:"green", size:3, type:"C"}];
$('select#color').change(function(e){
var value = $(this).val();
var sizes = [];
var types = [];
$.each(data, function(i, val) {
if (val.color == value) {
// only add options once
if (!sizes.indexOf(val.size)
sizes.push(val.size);
if (!sizes.indexOf(val.type)
types.push(val.type);
}
});
// now you would have arrays with all the available options,
// which you could then use to render the select options.
// since I don't know about the exact usage this may or may not be optimal
// in your case.
// it's not a complete solution, but may help to get you started.
关于javascript - 选择一个选项时过滤其他选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1422876/