简体   繁体   English

jQuery希望触发选择框更改

[英]Jquery looking to trigger select box change

Hey ii have select box with long method binded to it to its the select box in the html looks like this : 嘿,具有长方法的选择框已绑定到它的html中的选择框,如下所示:

HTML: HTML:

<select id="select1">
  <option>First select Advertiser</option>
  <?php
     buildSelectOptionsFromPagination();  // Dynamically build the options list
  ?>
</select> 

Javascript: Javascript:

$('#select1').change(function(){
                alert('#select1');
                $('#innerP').remove();
                $('#innerH').remove();
                $('#waitmsg').append('  ...</h2></p>');
                $("#show_c ").attr("disabled", true);   


                 $.ajax({
                        url: 'observer.php',
                        data: "ctrl=in&v_id="+v_id,
                        success: function(data) {
                             var newData = "<option id=\"firstopt_insert\"> blah blah <\/option>" + data;
                             $('#in111').html(data);
                             $('#in222').trigger('change');

                        },
                        error: function (request, status, error) {
                            alert(request.responseText+"\nThere was an server error please refresh the page 1 ");
                        }                           
                });
            });

now i try to trigger this select box change method without success from out side i trigger 2 method , 1. select option by index with this which works great : 现在,我尝试从外部触发此选择框更改方法,但没有成功,我触发了2种方法,1.使用索引选择选项,效果很好:

$('#select1 option')[5].selected = true;

2 now i want to trigger the change method method without success like this : 2现在我想触发change方法method但没有成功,像这样:

$('#select1').trigger('change');
or 
$('#select1').bind('change', function(){ ; });

and its just don't trigger any thing , why ? 它只是什么都不会触发,为什么呢?

Change event is triggered when user selects an option. 当用户选择一个选项时,将触发更改事件。 It's not triggered when you are setting the value via jQuery val() method of by setting option's selected attribute to true. 通过jQuery val()方法将选项的selected属性设置为true来设置值时,不会触发该事件。 So you have to trigger change event manually. 因此,您必须手动触发更改事件。

Your code 您的密码

$('#select1').trigger('change');

should work. 应该管用。 Maybe, it doesn't because you code raising an error. 也许不是因为您的代码引发了错误。 This may happen in this place 这可能发生在这个地方

$('#select1 option')[5].selected = true;

because here you don't perform array's range checking. 因为这里您不执行数组的范围检查。

Better way is to select needed option by index like this: 更好的方法是按如下所示通过索引选择所需的选项:

$('#select1 > :nth-child(6)').prop('selected', true);

This way code wouldn't crach in case if there is no 6th option. 如果没有第六种选择,这种方式的代码就不会崩溃。

However, this fiddle , built from your example, works just fine. 但是,根据您的示例构建的这种小提琴效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM