代码之家  ›  专栏  ›  技术社区  ›  Parker

如何等待jQuery函数完成才能继续?

  •  0
  • Parker  · 技术社区  · 14 年前

    所以现在我有密码了

    $('[name=dept]').live('change',function() {
    $('#course').load('getCla.php?dept='+$(this).val());
    $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
    });
    

    基本上,它所做的是在选择一个值之后传播一个表单选择菜单。问题是,第三行没有它想要的操作,它试图在第二行填写完列表之前执行。

    有没有办法让第三行等到列表完成传播?(当填写列表时,重新格式化列表)。

    2 回复  |  直到 14 年前
        1
  •  5
  •   Nick Craver    14 年前

    使用的回调参数 .load() ,就像这样:

    $('#course').load('getCla.php?dept='+$(this).val(), function() { 
      $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
    });
    

    当响应返回并且 #course 元素具有新内容。如果出于任何原因需要,它还会从服务器接收返回的html作为第一个参数。

    另外,由于您的初始选择器非常昂贵,我强烈建议您 .delegate() 这里,像这样:

    $('body').delegate('[name=dept]', 'change', function() {
      $('#course').load('getCla.php?dept='+$(this).val(), function() { 
        $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
      });
    });
    
        2
  •  2
  •   John Hartsock    14 年前

    jQuery load()

    这样地:

    $('[name=dept]').live('change',function() {
      $('#course').load('getCla.php?dept='+$(this).val(), function (responseText, textStatus, xhr) {
        $('select.speedC').selectmenu({style:'dropdown',maxHeight: 250}); 
      });
    });