如何使用html dom为国家列表创建对象数组

How to create an object array for a country list using html dom?

本文关键字:列表 创建对象 数组 国家 何使用 html dom      更新时间:2023-09-26

被这个卡住了一段时间了。如有任何帮助,不胜感激。

我正在为我的网站与国家选项的选择元素。我有一个javascript文件与2对象数组国家列表(我不能在html文件中指定选项,只使用这个js文件):

var country_list = [
{"country_code": "CA", "country_name": "Canada"},
{"country_code": "UK", "country_name": "United Kingdom"},
{"country_code": "AU", "country_name": "Australia"},
{"country_code": "NZ", "country_name": "New Zealand"} ];

然后这是我的html文件:

<form name="form1">    
Country <select value="country_code" onclick="select_country()"></select>
</form>

国家名称必须在下拉列表中显示,而选项的值将是2个字母的国家代码。另外,澳大利亚必须默认选择。

这是我到目前为止所做的:

function select_country(){
var select = document.form1.createElement("SELECT");
select.setAttribute("id","mySelect");
document.form1.body.appendChild(select);
var option = document.form1.createElement("option");
option.setAttribute("value", "Canada");
var text = document.createTextNode("CAN");
option.appendChild(text);
document.form1.getElementById("mySelect").appendChild(option);
}

使用普通js很容易做到这一点:

var selectElem = document.createElement("select");
for (var i = 0; i < country_list.length; i++) {
    var option = document.createElement("option");
    option.text = country_list[i].country_name;
    option.value = country_list[i].country_code;
    if (option.text == "Australia") option.selected = true; //default option
    selectElem.appendChild(option);
}
document.form1.body.appendChild(selectElem);
 for (i=0; i <=country_list.length; i++){
    var select = document.form1.createElement("SELECT");
    select.setAttribute("id","mySelect"+i);
    document.form1.body.appendChild(select);
    var option = document.form1.createElement("option");
    option.setAttribute("value", country_list[i].country_name);
    var text = document.createTextNode(country_list[i].country_code);
    option.appendChild(text);
    document.form1.getElementById("mySelect"+i).appendChild(option);
 }

如果你想用jQuery来做:

var country_list = [{
    "country_code": "CA",
    "country_name": "Canada"
}, {
    "country_code": "UK",
    "country_name": "United Kingdom"
}, {
    "country_code": "AU",
    "country_name": "Australia"
}, {
    "country_code": "NZ",
    "country_name": "New Zealand"
}]
.forEach(function(e){
    $("<option value='"+ e.country_code+"'>"+e.country_name+"</option>")
    .appendTo("select");
});

小提琴