jQuery根据选择的另一个SELECT删除SELECT选项(需要支持所有浏览器)

说我有这个下拉列表:

 1 2 3  

我想要它,以便当用户选择1时,这是用户可以选择下拉2的东西:

  a b c  

或者,如果用户选择2:

  a b  

或者,如果用户选择3:

  b c  

我试过这里发布的代码: jQuery禁用基于Radio选择的SELECT选项(需要支持所有浏览器)

但它不适用于选择。

请帮忙! 谢谢!

更新:我真的很喜欢Paolo Bergantino的答案: jQuery禁用基于Radio选择的SELECT选项(需要支持所有浏览器)

反正有没有修改它来使用选择而不是单选按钮?

 jQuery.fn.filterOn = function(radio, values) { return this.each(function() { var select = this; var options = []; $(select).find('option').each(function() { options.push({value: $(this).val(), text: $(this).text()}); }); $(select).data('options', options); $(radio).click(function() { var options = $(select).empty().data('options'); var haystack = values[$(this).attr('id')]; $.each(options, function(i) { var option = options[i]; if($.inArray(option.value, haystack) !== -1) { $(select).append( $('').text(option.text).val(option.value) ); } }); }); }); }; 

这有效(在Safari 4.0.1,FF 3.0.13中测试):

 $(document).ready(function() { //copy the second select, so we can easily reset it var selectClone = $('#theOptions2').clone(); $('#theOptions1').change(function() { var val = parseInt($(this).val()); //reset the second select on each change $('#theOptions2').html(selectClone.html()) switch(val) { //if 2 is selected remove C case 2 : $('#theOptions2').find('option:contains(c)').remove();break; //if 3 is selected remove A case 3 : $('#theOptions2').find('option:contains(a)').remove();break; } }); }); 

美丽的用户界面:

  

您可以在添加类来存储与#theOptions1每个值相关的#theOptions1

  

然后这样做:

 $(function() { var allOptions = $('#theOptions2 option').clone(); $('#theOptions1').change(function() { var val = $(this).val(); $('#theOptions2').html(allOptions.filter('.option-' + val)); }); }); 

对于记录,您无法删除 Internet Explorer中选择列表中的选项 。

实际上,使用下面的代码将删除IE中的下拉选项,只要它不是所选的选项(如果不首先取消选择该选项,它将无法在“a”上工作):

 var dropDownField = $('#theOptions2'); dropDownField.children('option:contains("b")').remove(); 

您只需运行此选项以删除要在第一个组(theOptions1)的条件语句下删除的任何选项 – 如果选择其中一个,则运行以下行:

 var dropDownField = $('#theOptions2'); if ($('#theOptions1').val() == "2") { dropDownField.children('option:contains("c")').remove(); } if ($('#theOptions1').val() == "3") { $("#theOptions2 :selected").removeAttr("selected"); $('#theOptions2').val('b'); dropDownField.children('option:contains("a")').remove(); } 

-Tom

试试这个。 这肯定会奏效

  $(document).ready(function () { var oldValue; var oldText; var className = '.ddl'; $(className) .focus(function () { oldValue = this.value; oldText = $(this).find('option:selected').text(); }) .change(function () { var newSelectedValue = $(this).val(); if (newSelectedValue != "") { $('.ddl').not(this).find('option[value="' + newSelectedValue + '"]').remove(); } if ($(className).not(this).find('option[value="' + oldValue + '"]').length == 0) { // NOT EXIST $(className).not(this).append(''); } $(this).blur(); }); });