填充第二选择框-绑定问题 [英] Populating a 2nd select box - binding problem
问题描述
我正在使用以下代码在城市中填充第二个选择框:
I'm using the following code to populate a 2nd select box with cities:
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解决了所有这一切.
Populating the list box works fine. But the alert does not output the new city (after country selection). Can this be a binding problem? I thought using $.live solved all this.
似乎在更新城市列表框之前已触发alert().我在做什么错了?
It looks like the alert() is triggered before the city list box is updated. What am I doing wrong?
推荐答案
史蒂文,您说得很对.代码:
Steven, you are exactly right. The code:
alert(jQuery("select#city").val());
在您的get()请求与服务器的响应一起返回之前正在执行.您定义的用于填充城市列表的回调函数在收到响应之前不会运行.
is executing before your get() request has returned with a response from the server. The callback function you defined for populating your city list doesn't run until a response is received.
尝试创建另一个函数来显示您的警报,然后从get的回调中对其进行调用:
Try creating another function to display your alert, and call that from the get's callback:
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");
}
这篇关于填充第二选择框-绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!