[英]How to create an object array for a country list using html dom?
Got stuck with this one for awhile now. 现在卡住了一段时间。 Any help would be appreciated.
任何帮助,将不胜感激。
I am making a select element with country options for my website. 我正在为我的网站选择一个带有国家/地区选项的元素。 I have a javascript file with 2-object array country list (I can't specify the options in html file, only use this js file):
我有一个带有2对象数组国家列表的javascript文件(我无法在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"} ];
And then here is my html file: 然后这是我的html文件:
<form name="form1">
Country <select value="country_code" onclick="select_country()"></select>
</form>
Country names have to be showed on the dropdown list, while the values for the options will be 2-letter country codes. 国家名称必须显示在下拉列表中,而选项的值将是2个字母的国家/地区代码。 Plus, Australia has to be selected by default.
另外,默认情况下必须选择澳大利亚。
This is what I have been up to so far: 到目前为止,这是我一直在做的事情:
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);
}
You can do this pretty easily with vanilla js: 您可以使用vanilla 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);
}
If you would like to use jQuery to do it: 如果您想使用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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.