我想要两个下拉框。第二个根据第一个下拉列表中的选择进行填充。第一个下拉列表工作正常,但第二个下拉列表没有。有人可以帮我这个吗?
HTML:
<div class="container-fluid">
<div class="row">
<div class="col-sm-2 col-md-2 col-lg-2">
<div class="dropdown" id="villageselector">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Village <span class="caret"></span></button>
<ul class="dropdown-menu">
</ul>
</div>
</div>
<div class="col-sm-2 col-md-2 col-lg-2">
<div class="dropdown" id="farmerselector">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Farmer <span class="caret"></span></button>
<ul class="dropdown-menu">
</ul>
</div>
</div>
</div>
</div>
JS:
//Populate the first dropdown
$.each(villagelist, function() {
$('#villageselector ul').append('<li><a data-villagename="'+ this.village+'" data-id = "'+this.id+'">' + this.village + '</a></li>');
});
//Add selector on the first dropdown
$('#villageselector a').click(function(){
selectedvillagename = $(this).data().villagename;
//Populate the second dropdown, based on the selection on the first dropdown
$.each(villagelist, function() {
if (this.village === selectedvillagename) {
for(i=0; i<this.farmernames.length; i++){
$('#farmerselector ul').append('<li><a data-farmername="'+ this.farmernames[i]+'" data-id = "'+i+'">' + this.farmernames[i] + '</a></li>');
}
}
});
});
$('#farmerselector a').click(function(){
//the list gets populated, but on selecting one of them, the code never reachers here
});
答案 0 :(得分:1)
您需要将$('#farmerselector a')
点击处理程序更改为委派的事件处理程序$(document).on('click', '#farmerselector a', function () //...
有关详细信息,请参阅https://learn.jquery.com/events/event-delegation/。