无法console.log事件目标名称

时间:2018-09-17 13:42:59

标签: javascript

所有人。

当我在表单中选择一个选项时,我想作为一个大陆名称。我决定使用e.target.value来获取名称,但是我遇到了一个问题。我无法在控制台中获得任何东西,也不知道问题出在哪里。 这是我的代码:

const selectPart = document.getElementsByClassName("selectPart");
for (let i = 0; i < selectPart.length; i++) {
  selectPart[i].addEventListener('click', getTarget);
}

function getTarget(e) {
  e.preventDefault();
  let partName = e.target.value;
  console.log(partName);
}
<form>
  <select class="selectForm">
    <option disabled selected class="select">Which continent is your country located in?</option>
    <option class="selectPart">Asia</option>
    <option class="selectPart">Europe</option>
    <option class="selectPart">South America</option>
    <option class="selectPart">North America</option>
    <option class="selectPart">Africa</option>
    <option class="selectPart">Oceania</option>
    <option class="selectPart">Antarctica</option>
  </select>
</form>

3 个答案:

答案 0 :(得分:1)

问题与您的班级名称selectForm并在您的代码selectPart

var select = document.getElementsByClassName('selectForm')[0];

select.addEventListener('change',function(e){
var country = e.target.value;
console.log(country);
});
<form>
            <select class="selectForm">
                <option disabled selected class="select">Which continent is your country located in?</option>
                <option class="selectPart">Asia</option>
                <option class="selectPart">Europe</option>
                <option class="selectPart">South America</option>
                <option class="selectPart">North America</option>
      <option class="selectPart">Africa</option>
                <option class="selectPart">Oceania</option>
      <option class="selectPart">Antarctica</option>
            </select>

答案 1 :(得分:0)

类名(selectForm和selectPart)有误。 同样,“更改” EventListener侦听选定DOM元素上的更改,因此您可以访问在更改时选择的目标值。 更改JS代码,如下所示:

document.querySelector('.selectForm')
  .addEventListener('change', (e) => {
    console.log(e.target.value);
});

答案 2 :(得分:0)

问题是选项标签没有很好地支持onClick事件,要实现所需的功能,您可以在select上切换为使用onChange侦听器

const selectPart = document.getElementsByClassName("selectForm");
selectPart[0].addEventListener('change', getTarget);

function getTarget(e) {
  e.preventDefault();
  let partName = e.target.value;
  console.log(partName);
}
<form>
  <select class="selectForm">
    <option disabled selected class="select">Which continent is your country located in?</option>
    <option class="selectPart">Asia</option>
    <option class="selectPart">Europe</option>
    <option class="selectPart">South America</option>
    <option class="selectPart">North America</option>
    <option class="selectPart">Africa</option>
    <option class="selectPart">Oceania</option>
    <option class="selectPart">Antarctica</option>
  </select>
</form>