点击事件监听器发生在加载而非点击时

时间:2019-02-23 23:40:35

标签: javascript html css

我试图在单击drumkey元素时更改p类的backgroundColor。但是,它是在加载页面而不是onClick时立即应用的。

var keyEl = document.getElementsByClassName("drumKey");
var x = document.getElementsByTagName("p");

for (i = 0; i < x.length; i++) {
    x[i].addEventListener("click", colorChange(i));
}

function colorChange(i) {
    keyEl[i].style.backgroundColor = "red";
}

2 个答案:

答案 0 :(得分:3)

这是因为addEventListener requires a function as a second parameter和您正在调用以执行一个函数而不是返回一个函数。

请记住functions are objects in Javascript。您可以只返回如下函数:

var keyEl = document.getElementsByClassName("drumKey");
var x = document.getElementsByTagName("p");

for (i = 0; i < x.length; i++) {
    x[i].addEventListener("click", colorChange(i));
}

function colorChange(i) {
  return function(){
    keyEl[i].style.backgroundColor = "red";
  }    
}
<div class="drumKey">This is div 1</div>
<div class="drumKey">This is div 2</div>
<div class="drumKey">This is div 3</div>
<div class="drumKey">This is div 4</div>


<p>Click here to change the background color to red of Div 1</p>
<p>Click here to change the background color to red of Div 2</p>
<p>Click here to change the background color to red of Div 3</p>
<p>Click here to change the background color to red of Div 4</p>

答案 1 :(得分:-2)

因此,您在分配事件时调用函数的错误,但是需要将其返回,如下所示

x[i].addEventListener("click", (i) => colorChange(i));