gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:28 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com