jQuery正在使用旧版本(1.3)不使用新版本(1.11.3)

时间:2017-04-03 06:50:06

标签: jquery version

var country = {
  "Choose Country": [{
    "city": "Choose City"
  }],
  "Australia": [{
    "city": "Brisbane"
  }, {
    "city": "Melbourne"
  }, {
    "city": "Sydney"
  }],
  "Bahrain": [{
    "city": "Hamad Town"
  }, {
    "city": "Manama"
  }, {
    "city": "Muharraq"
  }, {
    "city": "Riffa"
  }],
  "Canada": [{
    "city": "Calgary"
  }, {
    "city": "Montreal"
  }, {
    "city": "Toronto"
  }, {
    "city": "Vancouver"
  }]
};

function populateuser_city() {
  var region_code1 = $('#region_code1').val();
  var select = $('#user_city');
  var options = select.attr('options');
  $('option', select).remove();
  $.each(country[region_code1], function(index, array) {
    options[options.length] = new Option(array['city']);
  });
}

populateuser_city();

$('#region_code1').change(function() {
  populateuser_city();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="region_code1" name="region_code1" class="form-control" data-bv-message="Please select Country Code" required>
  <option>Choose Country</option>
  <option value="Australia">Australia (+61)</option>
  <option value="Bahrain">Bahrain  (+973)</option>
  <option value="Canada">Canada (+1)</option>
</select>
<select id="user_city" name="user_city" class="form-control" data-bv-message="Please select City" required></select>

1 个答案:

答案 0 :(得分:0)

您的问题是因为var options = select.attr('options');在较新版本的jQuery中返回undefined。您可以通过替换select元素的HTML而不是修改其中的现有option元素来解决此问题并改进逻辑。试试这个:

&#13;
&#13;
var country = {
  "Choose Country": [ 
    { "city": "Choose City" }
  ],
  "Australia": [ 
    { "city": "Brisbane" }, 
    { "city": "Melbourne" }, 
    { city": "Sydney" }
  ],
  "Bahrain": [
    { "city": "Hamad Town" }, 
    { "city": "Manama" }, 
    { "city": "Muharraq" }, 
    { "city": "Riffa" }
  ],
  "Canada": [
    { "city": "Calgary" }, 
    { "city": "Montreal" }, 
    { "city": "Toronto" }, 
    { "city": "Vancouver" }
  ]
};

$('#region_code1').change(function() {
  var region_code1 = $('#region_code1').val();
  var html = ''
  country[region_code1].forEach(function(country) {
    html += '<option>' + country.city + '</option>';
  })
  $('#user_city').empty().html(html);
}).change();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="region_code1" name="region_code1" class="form-control" data-bv-message="Please select Country Code" required>
  <option>Choose Country</option>
  <option value="Australia">Australia (+61)</option>
  <option value="Bahrain">Bahrain  (+973)</option>
  <option value="Canada">Canada (+1)</option>
</select>
<select id="user_city" name="user_city" class="form-control" data-bv-message="Please select City" required></select>
&#13;
&#13;
&#13;