我试图有两个下拉框。根据第一个下拉列表中的选择填充第二个。第一个下拉菜单可以正常工作,但第二个下拉列表则不能。有人可以帮我弄这个吗?

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
      });

最佳答案

您需要将$('#farmerselector a')单击处理程序更改为委托事件处理程序$(document).on('click', '#farmerselector a', function () //...

有关更多信息,请参见https://learn.jquery.com/events/event-delegation/

08-17 08:41