简体   繁体   English

在单击事件上从数组中选择随机元素不起作用

[英]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.做你做的方式就像:在JS进入taht代码行的那一刻,它会因为()而调用function,我建议在事件发生时调用它。

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.必须删除 (),因为当 JS 引擎在该行代码中时调用 function,而不是在加载 window 时调用。

Im not sure about the event of 'load' in that case I usually use 'DOMContentLoaded'在这种情况下,我不确定“加载”事件我通常使用“DOMContentLoaded”

mu line of code will be like this: mu 行代码将是这样的:

window.addEventListener('DOMContentLoaded', questionSelector);

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

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