javascript - 在html的select标签中调用javascript函数?

标签 javascript html

我有一个 javascript 文件(country.js),其中包含一些函数,例如 getcountry() 和 setcountry() 等。 getCountry 包含所有国家/地区的列表。现在我想使用此功能在我的网页上的组合框中显示所有国家/地区。但我不知道如何在 html 部分调用这个函数。

这是country.js文件的一部分

 ------------------Country.js--------------------------   
function _getCountries() {

}

function _setCountries() {
    _countries.push({ CountryID: 1, Name: 'Germany' });
    _countries.push({ CountryID: 2, Name: 'India' });
    _countries.push({ CountryID: 3, Name: 'China' });
    .................................................
}

我正在尝试类似的东西,但不知道如何在 html 部分使用这个函数。我是网络开发新手。

      -------------HTML--------------------------
      <div>
    <select onchange="Country()">

    //what to do in this section?
    </select>
   </div>

     ___________ javaScript__________________
    function Country{

           getCountries();
       //what to do in this section?
           }

最佳答案

_countries 是一个包含所有对象的数组。

_countries设为全局变量并在

中使用
function _getCountries() {
   return _countries;
}

var myDiv = document.getElementById("myDiv");

//Create array of options to be added
var array = [{ CountryID: 1, Name: 'Germany' },{ CountryID: 2, Name: 'India' },{ CountryID: 3, Name: 'China' }];

//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
myDiv.appendChild(selectList);

//Create and append the options
for (var i = 0; i < array.length; i++) {
    var option = document.createElement("option");
    option.setAttribute("value", array[i]);
    option.text = array[i].Name+"-"+array[i].CountryID;
    selectList.appendChild(option);
}
<div id="myDiv">Append here</div>

关于javascript - 在html的select标签中调用javascript函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609743/

相关文章:

javascript - 检索包含在存储库 ID 数组中的所有 github 存储库

javascript - 如何仅显示elfinder(jquery文件管理器插件)中的文件夹列表

javascript - 防止浏览器在刷新时自动滚动

javascript - Leaflet.js 从 AJAX 添加层

html - 左右边距 float DIV 中的 IE7 间距问题

html - 如何使导航栏中的链接垂直居中

javascript - 您如何为针对 ORM 的分页定义中继连接?

javascript - 给我看树.png

html - CSS 使用类和 id 隐藏一些文本

html - 在表行内垂直对齐