Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - Pass arguments in forEach -> eventlistener function

How can I solve this?

The code:

answerArr.forEach((div, index) => {
    div.addEventListener('click', () => {
      checkAnswer(div, index);
    });
  });

This works, but my function runs four times. (because I have four divs - in my array, in DOM)

How can I achieve this result: (run function only one but still have EventListener for each div)

answerArr.forEach((div, index) => {
    div.addEventListener('click', checkAnswer(div, index));
  });

I know I can't pass arguments to EventListener.

Thanks!

question from:https://stackoverflow.com/questions/65925850/pass-arguments-in-foreach-eventlistener-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...