如何使用html dom为国家列表创建对象数组
How to create an object array for a country list using html dom?
被这个卡住了一段时间了。如有任何帮助,不胜感激。
我正在为我的网站与国家选项的选择元素。我有一个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");
});
小提琴
相关文章:
- 在创建对象后附加一个jquery事件
- 错误:自动化服务器可以't创建对象
- 如何在不使用 new 关键字的情况下从函数创建对象
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 创建对象函数原型和代码是错误的
- 使用Undercore创建对象集合
- 如何在JavaScript中创建对象时使用变量的值
- 正在创建对象的递归列表
- 这两种不同的创建对象文字的方法有什么区别
- ES6 const,用于在JavaScript中创建对象原型;这是一种模式吗
- 使用字符串作为名称创建对象
- 使用参数创建对象
- 从 Dojo 中的对象列表创建表的最佳方法
- 如何创建一个javascript函数,输出一个带有object's属性列表的对象列表
- 如何在 JavaScript 中创建对象列表
- 如何使用html dom为国家列表创建对象数组
- 使用angularjs创建对象列表
- 如何创建对象列表的javascript数组
- javascript从文件列表创建文件列表对象
- 在Javascript中创建对象列表