jquery触发器更改与链式ajax选择

时间:2015-03-10 11:59:19

标签: php jquery ajax

我正在以这种方式使用一个选择并且效果很好。

$(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>

AJAX.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,但触发事件不执行任何操作。 我怎么解决?谢谢

1 个答案:

答案 0 :(得分:1)

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();
});
相关问题