Alert Event Listener取决于选择的选项JavaScript [duplicate]

问题描述 投票:0回答:1

我正在学习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>

此练习,但我不知道如何添加事件侦听器,该事件侦听器将使用选择列表中选择的国家/地区触发警报。

说明是:

  1. 使用innerHTML属性将所有这些国家/地区添加到#mySelect选择中。
  2. 然后,在'change'事件中添加一个侦听器,并在用户选择时显示并提醒所选国家/地区。
javascript dom onclick javascript-events onchange
1个回答
0
投票

您可以如下更新代码:-

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)
});
© www.soinside.com 2019 - 2024. All rights reserved.