我有一个动态创建select元素的ajax调用。选择量取决于另一个选择。这很好用。对于我的测试3选择菜单应该动态创建,工作正常。动态创建的选择将自己进行ajax调用以动态创建一些选项,这就是我遇到问题的地方。一切似乎都在工作,除了第二个选择的选项没有填充。请参阅下面的代码。
谢谢
$('#union').on('change',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$('#allreferee'+i).on('change', function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(html){
alert(html);/// this is good.. returns option values
$('#refposition'.i).html(html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
答案 0 :(得分:0)
您必须添加选择器参数,否则直接绑定事件而不是委托,这仅在元素已存在时才有效(因此它不适用于动态加载的内容)。查看this for more details
您的代码现在应该是这样的
$(document.body).on('change','#union',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$(document.body).on('change','#allreferee'+i, function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(data){
alert(html);/// this is good.. returns option values
$('#refposition'+i).html(data.html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
答案 1 :(得分:0)
我确定您的方法存在缺陷,但如果您必须:
$('#union').change(function(){
var union_id = $(this).val();
if(union_id !== ''){
$.post('fetch_referee.php', 'union_id='+union_id, function(data){
$('#dynamic_selects').html(data.html);
$('[id^=allreferee').change(function(){ // I would give the Elements an HTML class instead - but
var t = $(this), all_games = t.val();
// console.log(all_games); // this is good output is valid ??
if(all_games === ''){
t.html("<option value=''></option>");
}
else{
$.post('fetch_places.php', 'all_games='+all_games, function(html){
// console.log(html); // this is good.. returns option values ??
t.html(html); // the select menu does get updataded ??
}, 'json');
}
});
}, 'json');
}
});