简体   繁体   中英

Picking random elements from array on click event not working

I have written some question generator functions which work fine. Then put those functions in an array, when the user clicks the new question button it is supposed to pick a random question type from the array, but it is only randomising when I load the page rather than click the button. Thanks in advance.

let questionArray =[questionTypeZero, questionTypeOne];
function questionSelector(){
   return questionArray[Math.floor(Math.random()*2)]
};
window.addEventListener('load', questionSelector());
newQuestion.addEventListener('click', questionSelector() );

you have to change this line:

newQuestion.addEventListener('click', questionSelector() );

has to be this way:

newQuestion.addEventListener('click', questionSelector);

doing the way you did is like: in the moment when JS goes in taht line of code it will call the function because of the (), on the way I suggest it will be called when the event.

also in this line of code

window.addEventListener('load', questionSelector());

havo to remove the (), because is callign the function when JS engine is in that line of code, NOT when the window is loaded.

Im not sure about the event of 'load' in that case I usually use 'DOMContentLoaded'

mu line of code will be like this:

window.addEventListener('DOMContentLoaded', questionSelector);

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