问题描述
很抱歉,我想不出更好的方式来形容。在页面上,我有多个选择下拉列表。选择一个会影响第二个,选择第二个会影响第三个,依此类推...以最后的动作在“ end”处使用所有三个选择的值进行操作。我想出了以下似乎有效的方法,但我必须相信有更好的方法来处理此问题。
伪代码,但是您应该知道。我会以各种方式使用它,例如显示数据表或根据“ complete()”中每个选择的值显示图表。
html
<select id="one" name="one">
some options here
</select>
<select id="two" name="two">
some options here
</select>
<select id="three" name="three">
some options here
</select>
jquery
$('#one').on("change",function (e) {
two();
});
$('#two').on("change",function (e) {
three();
});
$('#three').on("change",function (e) {
complete();
});
function one() {
...maybe change options of two or something else
$('#two').trigger('change');
}
function two() {
...maybe change options of three or something else
$('#two').trigger('change');
}
function three() {
...do something
$('#three').trigger('change');
}
function complete() {
...use values from all three to do something
}
为清楚起见添加了更多信息:
无论更改了什么选择,我都需要对其进行“检查”,然后对其进行每次检查,直到完成整个操作为止。例如,如果我更改了1,那么我将其选中,然后是2,然后是3,然后运行完成。如果更改了2,则检查它,然后检查3,然后运行完成。如果3更改了,我检查一下,然后运行完成。
示例:用户将1更改为选项值“ dogs”,因为其中选择了dogs,所以我知道将2中的选项更改为dog类型,并且由于dog类型在2中显示,因此我将选项更改为3颜色...然后我完成。在这种情况下完成将给我所有类型的狗,所有颜色的狗。
现在,假设他们将2更改为“斗牛”的值,因为现在他们可以使用该选项。因此,我检查其值并更改3以仅显示所有选项(白色和黑色),然后运行完整。完成后,我得到了狗,斗牛犬和所有颜色作为值。
我要了解的是,当任何选择更改时,我可能会基于该更改在选择之后进行更改-就像它们都链接在一起一样-我需要在每个选择上都做到完整。
我将使用它来根据选择显示表格和/或图表。因此,在每次更改时,我都会检查之后的所有选择,获取值,然后更新表/图表。
解决方法
方法很多。
<script>
function complete() {
jQuery( "select" ).each(function( index ) {
var _this = jQuery(this);
console.log("SELECT_BOX " + _this.attr('name') + ':' +_this.val());
});
}
jQuery('select').on('change',function(){
var _this = $(this);
if(_this.next('select').length){
//Here We are adding active class to the next select box,you can change as per requirement
_this.next('select').addClass('active');
}
else{
//When you reach to the last select box
complete();
}
})
</script>