简体   繁体   English

通过for循环将事件监听器应用于按钮?

[英]Apply Event Listeners to buttons via for loop?

I am trying to apply event listeners to an array of buttons, as depicted below. 我正在尝试将事件侦听器应用于按钮数组,如下所示。 The console logging works just fine, but when I get to the for loop, the event listeners aren't added to the button s to function as intended. 控制台日志记录工作正常,但是当我进入for循环时,未将事件侦听器添加到button以按预期方式工作。

I don't see my mistake, and any help would be appreciated. 我没有看到自己的错误,我们将不胜感激。

<button onclick="" id="optContrastButton" data-style="contrast">reset</button>

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

let buttons = document.getElementById('optWindow').getElementsByTagName('button');
console.log(buttons);
for(let b = 0; b < buttons.length; b++) {
  let data = buttons[b].dataset.style;
  console.log(data); // Data returned 'contrast' :: OKAY
  buttons[b].addEventListener('onclick', function() {
    document.querySelector('#innerWindow').style.webkitFilter = `${data}(1)`;
    let c = data.capitalize();
    console.log(`#opt${c}Range`); // No Data returned :: FAIL :(
    document.querySelector(`#opt${c}Range`).value = 1;
  });
}

The two modern vanilla JS methods for adding event listeners are the raw assignment: 用于添加事件侦听器的两种现代香草JS方法是原始分配:

el.onclick = function() {...} // note the prefix `on`

and using addEventListener: 并使用addEventListener:

el.addEventListener('click', function() {...}) // note: no `on` prefix!

You're mixing up the two and using the prefixed version ( onclick ) in addEventListener. 您将两者onclick在addEventListener中使用了前缀版本( onclick )。 So the fix: Change 因此解决方法:更改

buttons[b].addEventListener('onclick', function() {

to

buttons[b].addEventListener('click', function() {

Event names don't start with on . 事件名称不下手on You need to listen for the "click" event, not the "onclick" event. 您需要侦听"click"事件,而不是"onclick"事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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