Jquery 填充第二个选择框-绑定问题

Jquery 填充第二个选择框-绑定问题,jquery,Jquery,我使用以下代码在第二个选择框中填充城市: jQuery('#country').live("change", function(){ populateCityListBox(); alert(jQuery("select#city").val()); }); - - - - - - - - - - - - - - - function populateCityListBox() { jQuery.get("my/path/myfile.php"

我使用以下代码在第二个选择框中填充城市:

  jQuery('#country').live("change", function(){ 
    populateCityListBox();
    alert(jQuery("select#city").val());
  }); 

- - - -  - - - - - - - - - - -

  function populateCityListBox()
  {

    jQuery.get("my/path/myfile.php", { instance: 'getCitiesByCountry', countryID: jQuery("select#country").val(), brandID: $_GET('brandID') },
      function(data)
      {
          var options = '';
          for (var i = 0; i < data.length; i++) {
            if (i == 0)
              options += '<option selected value="' + data[i].city + '">' + data[i].city + '</option>';
            else
              options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';

          }

          jQuery("select#city").append(options);
      },"json");
  }
填充列表框效果很好。但在选定国家后,警报不会输出新城市。这会是一个绑定问题吗?我以为用$.live解决了这一切


看起来警报是在更新城市列表框之前触发的。我做错了什么?

史蒂文,你完全正确。守则:

alert(jQuery("select#city").val());
在get请求返回服务器响应之前执行。为填充城市列表而定义的回调函数在收到响应之前不会运行

尝试创建另一个函数来显示警报,并从get的回调调用该函数:

  jQuery('#country').live("change", function(){ 
    populateCityListBox();
  }); 

function showCity()
{
    alert(jQuery("select#city").val());
}

- - - -  - - - - - - - - - - -

  function populateCityListBox()
  {

    jQuery.get("my/path/myfile.php", { instance: 'getCitiesByCountry', countryID: jQuery("select#country").val(), brandID: $_GET('brandID') },
      function(data)
      {
          var options = '';
          for (var i = 0; i < data.length; i++) {
            if (i == 0)
              options += '<option selected value="' + data[i].city + '">' + data[i].city + '</option>';
            else
              options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';

          }

          jQuery("select#city").append(options);
          showCity();
      },"json");
  }

您正在使用AJAX调用填充城市列表框。除非更改默认值,否则调用是异步的;因此,不能保证它在调用警报之前完成

最好在成功回调中调用alert,将其作为第三个参数传递:

jQuery.get(your_url, your_data, function() {alert('...');})

这段代码对我很有用。我所做的唯一修改是在执行追加之前放置.empty,如下所示:

function populateCityListBox()
 {

  jQuery("select#city").empty();
 ....

否则,如果更改选择,新值将附加到现有值。

好的,谢谢。这确实奏效了。我需要做的是用选定的城市更新谷歌地图。将showCity替换为updateMap works。但我并不喜欢将它添加到PopulateCityList框中——只是似乎放错了地方。