使用javascript的html5下拉列表

时间:2013-07-13 16:22:34

标签: javascript jquery html5

我必须在html页面中显示250个国家/地区的下拉列表。我可以通过下面的方式轻松完成

<select id="country" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
.....
<option value="250">Canary Islands</option>
</select>

我必须在html页面中使用相同列表的5倍。那么,我怎样才能减少重复工作?

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery的克隆来克隆元素:http://api.jquery.com/clone/

for(var i=0; i<5; i++) {
  $("body").append($("#country").clone(false).prop("id", "country"+i));
}

这将克隆国家/地区下拉列表5次,更改每个国家/地区的ID属性以使其唯一,然后将其附加到页面。

答案 1 :(得分:0)

这是普通人的另一种选择。 JavaScript的:

var cloneList = function(){
 return this.cloneNode();
}.bind(document.getElementById('country'));

var count = 5;
while(count--) document.body.appendChild(cloneList()).id = 'country' + count;

您可以在需要时重用cloneList函数。