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

Call a javascript function in select tag of html?

本文关键字:调用 javascript 函数 标签 html select      更新时间:2023-09-26

我有一个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部分使用这个函数。我是web开发新手。

      -------------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>