1

我想将'change'事件添加到 4 个选择框。我已经使用bind(). 但是我想在更改每个选择框时调用不同的函数。对...的更改事件说function1()SelectBox1

我该怎么做?

我是&的新手,所以请帮忙。谢谢javascriptjquery

4

2 回答 2

1

假设你的 HTML 是这样的:

HTML

<select id="selectBox1">
</select>

<select id="selectBox2">
</select>

<select id="selectBox3">
</select>

<select id="selectBox4">
</select>

jQuery

$('select[id^=selectBox]').on('change', function() {

    // to get the id of current selectBox
    var selectId = this.id;

    if(selectId == 'selectBox1') {
        function1();
    } else if(selecId == 'selectBox2') {
       function2();
    }
    // and so on
});

多一点

$('select[id^=selectBox]').on('change', function() {
     
        // to get the selected value
        var value = $.trim( this.value ); // $.trim() used to remove space
                                          // from beginning and end
                                          // you may not use

        // to get selected option text
        var optText = $('option:selected', this).text()


        // to get the selectedIndex
        var selIndex = this.selectedIndex;
        // OR
        var selIndex = $(this).prop('selectedIndex');
});

笔记

在这里,获取以 .开头的select[id^=selectBox]选择框。你可能有不同的东西。idselectBoxid

.change()用于将事件绑定到那些选择框。

阅读更多关于

于 2012-06-08T06:16:26.627 回答
0

您可以为每个选择设置一个特定的属性,这样:

<select id="selectBox1" val='1'>
</select>

<select id="selectBox2" val='2'>
</select>

<select id="selectBox3" val='3'>
</select>

<select id="selectBox4" val='4'>
</select>

然后像这样绑定 onchange 事件:

  $("select").change(function(){
        var val = $(this).attr("val");
        if (val == '1')
            {
                //logic for first select change
            }
        else if (val == '2')
            {
                //logic for second select change
            }
        else if (val == '3')
            {
                //logic for third select change
            }

        // and so on...
   });

希望有帮助。

于 2012-06-08T06:38:22.100 回答