JQuery - 选择先前数据后的加载选项

时间:2014-11-07 23:52:39

标签: jquery

我正在尝试在选择第一个选项后重新加载第二个选项。我使用.change jQuery事件,但它执行的顺序是随机的。对此有更好的事件处理吗?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

  $(document).ready(function() {
  // clearing the previous appends here.
  $('#names').empty(); 
     for(i=0; i<list.length; i++) { // assume list[i] contains different names
        var name_options = $('<option>' + list[i] + '</option>');
        $('#names').append(name_options);
     } // end of for loop

  /* I want to retrieve data when a particular option is selected. But this doesnt work*/
  $('#names').change(function(){
   var val = $(this).find(':selected').html();
  });

 /*Data for address is loaded after the previous data is selected*/
 $('#names').change(function(){
     // options for addresses are loaded here
 });

 $('#address').change(function(){
   var val = $(this).find(':selected').html();
  });
 });

 </script>
 </head>
 <body>
  <select id='names' class='combobox'>
   !-- options for names go here --> 
  </select>
  <select id='address' class='combobox'>
   !-- options for addresses go here. But after the name is selected --> 
  </select>
 </body>
 </html>

但#address选项似乎在名称加载之前尝试加载。有没有办法可以确保只在选择了#names之后才加载#address?

2 个答案:

答案 0 :(得分:0)

这是一个jsFiddle,说明了可能的答案。

该功能的核心如下所示。当names选项更改时,请清除之前的address个选择值,然后添加新值。

$('#names').change(function() {
    // options for addresses are loaded here
    $("#address").empty();
    var addresses = [ "123 Elm Street", "456 Oak Road" ];
    $.each(addresses, function(i, item) {
        var address_options = $('<option>' + item + '</option>');
        $('#address').append(address_options);
    });
});

答案 1 :(得分:0)

如果我理解你的问题,这就是你要找的吗?

FIDDLE

$(document).ready(function () {
    var list = [{
        value: 'Address 1',
        html: 'Name 1'
    }, {
        value: 'Address 2',
        html: 'Name 2'
    }];

    for (i = 0; i < list.length; i++) { // assume list[i] contains different names
        var name_options = $('<option value="' + list[i].value + '">' + list[i].html + '</option>');
        $('#names').append(name_options);
    } // end of for loop

    $('#names').change(function (e) {
        var theVal = $(this).val();
        $('#address').show().find('option').attr('value', theVal).html(theVal);
        $('#address').val(theVal);
    });

});

HTML

<select id='names' class='combobox'>
    <option value="">Please select name...</option>
</select>
<select id='address' class='combobox' style="display: none">
    <option value="">Waiting...</option>
</select>