You can use bind()
to ensure that the function is called with the arguments specified.
For example:
answerArr.forEach((div, index) => {
div.addEventListener('click', checkAnswer.bind(null, div, index));
});
The first argument to bind()
, null
in this case, is what you're binding the this
value of the function to. So if you reference this
from inside checkAnswer
, it'd refer to that first argument.
This example is assuming that you have 4 different divs that each need an event listener. If you just have one div, you could potentially just reverse the structure:
div.addEventListener('click', (event) => {
// here you can use the "event" arg to get info about what was clicked
checkAnswer();
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…