jQuery 使用链接的 AJAX Select 触发更改


jquery trigger change with chained ajax select

我以这种方式使用chanied select并且效果很好。

$(function() {
  /**
   * Chained Select (id_foo)
   *
   * @method on change
   */
  $('select[name="id_foo"]').on('change', function() {
      var id_foo = $("option:selected", this).prop("value");
      $.ajax({
          type    : "POST",
          url       : ajax.php,
          data    : { id_foo: id_foo },
          success : function(data) {
              $('select[name="id_bar"]').html(data);
          }
      });
  });
}); /* END */

.HTML

<select name="id_foo">
   <option value="1">one</option>
   <option value="2">two</option>
</select>
<br>
<select name="id_bar">
</select>

阿贾克斯。.PHP

if(isset($_POST['id_foo'])){
   $obj->selectBar($_POST['id_foo']);
}

现在我想使用触发器函数以这种方式模拟更改事件

$(function() {
  $('select[name="id_foo"]').val('2').trigger('change');
  /**
   * Chained Select (id_foo)
   *
   * @method on change
   */
   $('select[name="id_foo"]').on('change', function() {
   ...
   ...

但没有成功。select 的值为 2,但触发器事件不执行任何操作。我该如何解决?谢谢

val() 不返回 jQuery 对象。

而是做

$(function() {
  var $sel = $('select[name="id_foo"]');
  $sel.on('change', function() {
    var id_foo = this.value;
    $.ajax({
      type    : "POST",
      url       : ajax.php,
      data    : { id_foo: id_foo },
      success : function(data) {
          $('select[name="id_bar"]').html(data);
      }
    });
  });
  $sel.val('2');
  $sel.change();
});