简体   繁体   中英

Why am I not able to add an event listener in a loop?

const inputs = document.getElementsByClassName("uk-input")
for (let element of inputs) {
  element.addEventListener("onchange", e => {
    alert("test")
  })
}
console.log(inputs)

When I look at the output of the last line the "onchange" event listener field is null. What am I doing wrong?

Nor does typing into respective input fields produce an alert box.

The event name is change , not onchange :

const inputs = document.getElementsByClassName("uk-input")
for (let element of inputs) {
  element.addEventListener("change", e => {
    alert("test")
  })
}
console.log(inputs)

You would use onchange when assigning to the property name of onchange to add the listener, eg:

const inputs = document.getElementsByClassName("uk-input")
for (let element of inputs) {
  element.onchange = e => {
    alert("test")
  };
}
console.log(inputs);

(but this probably isn't a great idea, because this will overwrite previous listeners attached by assigning to onchange , and future code that may assign to onchange will overwrite your listener - best to use addEventListener instead.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM