繁体   English   中英

jQuery希望触发选择框更改

[英]Jquery looking to trigger select box change

嘿,具有长方法的选择框已绑定到它的html中的选择框,如下所示:

HTML:

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

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 ");
                        }                           
                });
            });

现在,我尝试从外部触发此选择框更改方法,但没有成功,我触发了2种方法,1.使用索引选择选项,效果很好:

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

2现在我想触发change方法method但没有成功,像这样:

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

它只是什么都不会触发,为什么呢?

当用户选择一个选项时,将触发更改事件。 通过jQuery val()方法将选项的selected属性设置为true来设置值时,不会触发该事件。 因此,您必须手动触发更改事件。

您的密码

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

应该管用。 也许不是因为您的代码引发了错误。 这可能发生在这个地方

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

因为这里您不执行数组的范围检查。

更好的方法是按如下所示通过索引选择所需的选项:

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

如果没有第六种选择,这种方式的代码就不会崩溃。

但是,根据您的示例构建的这种小提琴效果很好。

暂无
暂无

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

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