如何在JavaScript中使用数组创建国家列表?我在第页中有10个或更多选择国家/地区框

trnvg8h3  于 2023-05-12  发布在  Java
关注(0)|答案(2)|浏览(137)

如何使用数组创建国家列表?我有总数10或更多选择国家框在页。我想创建一个类的名字。

var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa" /*, ... */ );

function country() {
  var x = "<option disabled>Select Country</option>";
  
  for (var i = 0; i < country_arr.length; i++) {
    var node = country_arr[i];
    x += "<option value='" + country_arr[i] + "'> " + country_arr[i] + " </option>"
  }

  var countryElement = document.getElementsByClassName('country');
  countryElement.innerHTML = x;
  document.getElementsByClassName("country").innerHTML = x;
}
<div style='text-align:center;'>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
</div>

<script>
  country();
</script>
cigdeys3

cigdeys31#

下面的代码将循环遍历数组,创建一个选项,然后使用.country将其附加到所有选择。这个解决方案使用jquery。

var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa");

country_arr.forEach( function(obj) {
  var temp_country = new Option(obj, obj);
  $(temp_country).html(obj);
  $("select.country").append(temp_country);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="country" name ="country"></select>
<select class="country" name ="country"></select>
<select class="country" name ="country"></select> </div>
ee7vknir

ee7vknir2#

您需要迭代使用document.getElementsByClassName("country")获得的HTMLCollection元素:

var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa" /*, ... */ );

function country() {
  var x = "<option disabled>Select Country</option>";
  
  for (var i = 0; i < country_arr.length; i++) {
    var node = country_arr[i];
    x += "<option value='" + country_arr[i] + "'> " + country_arr[i] + " </option>"
  }
  
  let list = document.getElementsByClassName("country");
  for (let item of list) {
    item.innerHTML = x;
  }

}

country();
<div style='text-align:center;'>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
</div>

相关问题