jQuery根据在更改和加载时选择的另一个SELECT删除SELECT选项

时间:2010-06-09 23:38:41

标签: javascript jquery

我正在使用以下jQuery代码从select中删除选项,它运行良好。但是它不仅仅是在更改了Option2选项时执行,而是根据所选择的项目加载页面时我也希望它能够工作。我尝试使用脚本的副本并将.change更改为.load并尝试使用(窗口).load而没有所需的结果。本质上,我需要脚本在更改Options1和加载页面时执行。对此的任何帮助将不胜感激。

<script type="text/javascript">
    $(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;
        }
    });
});

</script>

<select id="theOptions1">
  <option value="1">1</option>
  <option value="2" selected="selected">2</option>
  <option value="3">3</option>
</select>
<br />
<select id="theOptions2">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>

1 个答案:

答案 0 :(得分:4)

$(document).ready(...

结尾处触发事件
$('#theOptions1').trigger('change');