如何使用javascript数组中的选项(国家/地区)创建下拉列表(HTML) [英] How do I make a dropdown list (HTML) with options (countries) from a javascript array

查看:85
本文介绍了如何使用javascript数组中的选项(国家/地区)创建下拉列表(HTML)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML中创建一个表单,询问您的姓名,姓氏和国家。

姓名没有问题,但是国家/地区。我希望(需要)使用世界上所有国家/地区的下拉列表,下拉列表的选项是来自javascript数组的所有元素。



我制作js文件的方式是这样的:我做了一个函数init(){

let list_countries = ['afghanistan' ,...]所以我在所有国家/地区制作了一个var list_functions,之后我运行了函数

init()。



问题是,如何在下拉列表中将这些国家/地区作为一个选项?我想用html标签做这部分编码



我尝试过:



我尝试过这样的事情:

I want to make a form in HTML that asks your name, last name and country.
Names are no problems, but countries are. I want (need) to use a dropdown list with all the countries of the world, the options of the dropdown list are all elements from a javascript array.

The way I made the js file is like this: i made a function init(){
let list_countries=['afghanistan',...] so I made a var list_functions with all the countries, after that I ran the function
init().

The thing is, how can I represent each of these countries as an option in my dropdown list? I'd like to do this part of coding in html tags

What I have tried:

I tried things like:

<select id="country_list"></select>
    <script src="script.js">
    </script> 
</select><br></br>



我尝试交换选择和脚本等,但我不知道:/



我尝试用Google搜索/在线查找解决方案,但我找不到一个完美的解决方案。


I tried swapping select and script etc, but I have no clue :/

I tried googling/finding the solution online, but I can't find a perfect solution to my question.

推荐答案

这是一个想法:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
<script type="text/javascript">
  function countries_ddl() {
     var countries = ["England", "France", "Germany"];
     var select = document.getElementById('country_list');
     for (var i = 0; i < countries.length; i++) {
        var opt = document.createElement('option');
        opt.value = i;
        opt.innerHTML = countries[i];
        select.appendChild(opt);
     }
}
</script>
</head>
<body onload="countries_ddl()">
		<select id="country_list">
         <option value="0">- please select -</option>
		</select>		
</body>
</html>


这篇关于如何使用javascript数组中的选项(国家/地区)创建下拉列表(HTML)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆