我正在学习JS事件,并将它们放入HTML。我在做
var myCountriesSelect = document.querySelector("#mySelect");
function init() {
var countries = ['USA', 'France', 'Italy', 'Brazil', 'Colombia', 'Belize', 'Venezuela'];
for (var i = 0; i < countries.length; i++) {
var opt = countries[i];
var el = document.createElement("option");
el.innerHTML = opt;
el.value = opt;
myCountriesSelect.appendChild(el);
}
}
@charset "UTF-8";
body {
text-align: center;
background-size: cover;
}
select {
-moz-appearance: none;
-webkit-appearance: none;
text-indent: 0.01px;
text-overflow: '';
padding: 1em 0 1em 1em;
border: 1px solid #107177;
border-radius: 0;
position: relative;
border-right-width: 20px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
font-weight: bold;
text-transform: uppercase;
}
select:focus {
outline: none;
border-color: #169ca4;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
</head>
<body onload="init();">
<select id="mySelect">
<option value="-1">Select your country</option>
</select>
</body>
</html>
此练习,但我不知道如何添加事件侦听器,该事件侦听器将使用选择列表中选择的国家/地区触发警报。
说明是:
您可以如下更新代码:-
var myCountriesSelect = document.querySelector("#mySelect");
function init() {
var countries = ['USA', 'France', 'Italy', 'Brazil', 'Colombia', 'Belize', 'Venezuela'];
for (var i = 0; i < countries.length; i++) {
var opt = countries[i];
var el = document.createElement("option");
el.innerHTML = opt;
el.value = opt;
myCountriesSelect.appendChild(el);
}
}
myCountriesSelect.addEventListener("change", function(event){
alert(event.target.value)
});