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

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

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 += '' + data[i].city + ''; else options += '' + data[i].city + ''; } jQuery("select#city").append(options); },"json"); } 

填充列表框工作正常。 但警报不会输出新城市(在国家选择之后)。 这可能是一个绑定问题吗? 我以为使用$ .live解决了这一切。

看起来在更新城市列表框之前触发alert()。 我究竟做错了什么?

史蒂文,你说得对。 代码:

 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 += ''; else options += ''; } jQuery("select#city").append(options); showCity(); },"json"); } 

您正在使用AJAX调用来填充城市列表框。 除非您更改了默认值,否则调用是异步的; 因此,无法保证在调用alert()之前完成它。

最好在成功的回调中调用alert(),并将get()作为第三个参数传递给它:

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

这段代码对我来说非常有用。 我做的唯一修改是在执行追加之前添加.empty ,如下所示:

 function populateCityListBox() { jQuery("select#city").empty(); .... 

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