2016-11-15 80 views
1

我有一個JavaScript文件(country.js),它有一些函數,如getcountry()和setcountry()等。getCountry具有所有國家的列表。現在我想使用此功能在我的網頁上顯示組合框中的所有國家。但我不怎麼在html部分調用這個函數。在html的select標籤中調用javascript函數?

這是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? 
      } 

回答

1

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