简体   繁体   English

如何在单击按钮时调用随机 function?

[英]How do I call a random function on button click?

Here is a quick background on project goals: I'm trying to build a simple math game that provides random math problems when you click on a button.以下是项目目标的简要背景: 我正在尝试构建一个简单的数学游戏,当您单击按钮时会提供随机数学问题。 Later, I'll figure out a way to check whether the answers are correct.稍后,我会想办法检查答案是否正确。 I started this process by creating an input form.我通过创建一个输入表单开始了这个过程。

I'm trying to call a random function in a javascript array using a button in HTML.我正在尝试使用 HTML 中的按钮在 javascript 数组中调用随机 function。 The button calls a random function that is decided when I refresh the page.该按钮调用一个随机 function ,这是在我刷新页面时决定的。 Once I refresh the page, the a function is randomly selected and the button continues to give the results of that function over and over.刷新页面后,随机选择 function 并且按钮继续一遍又一遍地给出 function 的结果。 The button only calls a different function if I refresh the page.如果我刷新页面,该按钮只会调用不同的 function。

I would prefer to have the button call a random function in my array each time the button is clicked.每次单击按钮时,我希望按钮在我的数组中调用随机 function 。 Anybody know how I could achieve this?有谁知道我怎么能做到这一点?

Here's my code:这是我的代码:

 const btn = document.querySelector('#START') const randomFunc = [ multiplication, division, addition, subtraction, ] btn.addEventListener( 'click', randomFunc[Math.floor(Math.random() * randomFunc.length)] ) function multiplication(params) { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 13); let problemResult = num1 * num2; console.log(num1, '*', num2, '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${num1} * ${num2} =`); } function division(params) { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 12) + 1; let problemResult = (num2 * num1) / num2; console.log(num1, '/', num2, '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${num1} / ${num2} =`); } function addition(params) { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 13); let problemResult = num1 + num2; console.log(num1, '+', num2, '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${num1} + ${num2} =`); } function subtraction(params) { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 13); let numList = [num1, num2]; numList.sort(function(a, b) { return b - a }); let problemResult = numList[0] - numList[1]; console.log(numList[0], '-', numList[1], '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${numList[0]} - ${numList[1]} =`); }
 <div> <button type="button" class="btn btn-primary btn-lg" id="START">Press here for your first problem</button> <script src={% static 'js/game_logic.js' %}></script> <p id="mathProblem">Your problem will appear here</p> <form action=""> <input type="text" placeholder="Type your answer here"> </form> </div>

Wrap it in another function that selects a random function each time the click happens.将其包装在另一个 function 中,每次单击时都会选择一个随机 function。

Also, your functions don't use params , so it's not needed.此外,您的函数不使用params ,因此不需要。

 const btn = document.querySelector('#START') const randomFunc = [ multiplication, division, addition, subtraction, ] btn.addEventListener( 'click', function() { randomFunc[Math.floor(Math.random() * randomFunc.length)](); } ) function multiplication() { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 13); let problemResult = num1 * num2; console.log(num1, '*', num2, '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${num1} * ${num2} =`); } function division() { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 12) + 1; let problemResult = (num2 * num1) / num2; console.log(num1, '/', num2, '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${num1} / ${num2} =`); } function addition() { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 13); let problemResult = num1 + num2; console.log(num1, '+', num2, '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${num1} + ${num2} =`); } function subtraction() { let num1 = Math.floor(Math.random() * 13); let num2 = Math.floor(Math.random() * 13); let numList = [num1, num2]; numList.sort(function(a, b) { return b - a }); let problemResult = numList[0] - numList[1]; console.log(numList[0], '-', numList[1], '=', problemResult); document.getElementById('mathProblem').innerHTML = (`${numList[0]} - ${numList[1]} =`); }
 <div> <button type="button" class="btn btn-primary btn-lg" id="START">Press here for your first problem</button> <script src={% static 'js/game_logic.js' %}></script> <p id="mathProblem">Your problem will appear here</p> <form action=""> <input type="text" placeholder="Type your answer here"> </form> </div>

Your code of:您的代码:

randomFunc[Math.floor(Math.random() * randomFunc.length)]

is not stored inside of a function, so as soon as the page loads and the script is initially parsed, that statement is executed and your random function name is retrieved from the array and that code will be replaced with whichever function name was gotten, so for the rest of that page's use, the code will actually be static and be evaluated like this: is not stored inside of a function, so as soon as the page loads and the script is initially parsed, that statement is executed and your random function name is retrieved from the array and that code will be replaced with whichever function name was gotten, so对于该页面使用的 rest,代码实际上是 static 并像这样评估:

// showing multiplication here, but will be whichever random name was initially returned
btn.addEventListener('click', multiplication)

But, once it's gotten, the initial randomizing code won't be executed again, because it will have already been replaced by the result of the first pass through parsing the script .但是,一旦获得,初始随机化代码将不会再次执行,因为它已经被第一次解析script的结果所取代。 So, in the end, you get one call for a random function reference and that result is what you stick with until the page is reloaded.因此,最后,您会接到一个随机 function 参考的电话,并且该结果是您在重新加载页面之前坚持的结果。

What you need is for that randomizing code to be executed every time the button is clicked, so by wrapping it in another function (which localizes the statement), that will happen:您需要的是每次单击按钮时执行随机化代码,因此通过将其包装在另一个 function (本地化语句)中,这将发生:

btn.addEventListener(
  'click', function() { randomFunc[Math.floor(Math.random() * randomFunc.length)](); }
)

Now, every time you click the button, randomFunc[Math.floor(Math.random() * randomFunc.length)] will get a new function name and () after it will cause it to be invoked because the whole expression is inside of an anonymous function expression , which will become the event handler.现在,每次单击按钮时, randomFunc[Math.floor(Math.random() * randomFunc.length)]都会获得一个新的 function 名称,并且()之后会导致它被调用,因为整个表达式都在一个匿名的 function表达式,它将成为事件处理程序。

Wrap with another function so that it gets executed on each click用另一个 function 包装,以便在每次点击时执行

btn.addEventListener('click', function () {
  randomFunc[Math.floor(Math.random() * randomFunc.length)]()
})

Your code set the random function only once (on page Load) so it's always the same when clicking the button您的代码仅将随机 function 设置一次(在加载页面上),因此单击按钮时始终相同

btn.addEventListener('click', randomFunc[Math.floor(Math.random() * randomFunc.length)])

it's because you're already generated a function and assigned it here这是因为您已经生成了 function 并在此处分配

btn.addEventListener(
'click', randomFunc[Math.floor(Math.random() * randomFunc.length)]
)

in order to randomize it you have to make a callback that generates a random function instead为了使其随机化,您必须进行回调以生成随机 function

btn.addEventListener(
  'click', function() {
    const a = randomFunc[Math.floor(Math.random() * randomFunc.length)];
    a();
  }
)

it should now work.它现在应该可以工作了。 https://jsbin.com/duyosiluna/edit?html,js,console,output https://jsbin.com/duyosiluna/edit?html,js,控制台,output

Have you tried using a arrow function, like so你试过用箭头function,像这样

btn.addEventListener(
  'click', () =>  randomFunc[Math.floor(Math.random() * randomFunc.length)]; 
)

This will also execute the function on each click这也将在每次点击时执行 function

The function addEventListener() adds one function to an HTML-Element when executed. function addEventListener()在执行时将一个 function 添加到 HTML 元素。

This means, when your addEventListener() -line is executed (which it only is once, when your script is executed for the first time), it selects one of your functions and adds only that.这意味着,当您的addEventListener() -line 被执行时(它只有一次,当您的脚本第一次执行时),它会选择您的一个函数并添加它。

To be able to select one of you functions repeatedly on click, you would need to instead add a function that selects on of yours, instead of adding one of yours directly.为了能够在单击时重复使用 select 您中的一个功能,您需要添加一个 function 来选择您的一个,而不是直接添加您的一个。 That way, the "selection"-function runs every time your button is clicked.这样,每次单击按钮时都会运行“选择”功能。

Here is an example:这是一个例子:

 var funcToSelect = [func1, func2, func3]; document.querySelector('button').addEventListener('click', () => { funcToSelect[Math.floor(Math.random() * funcToSelect.length)](); }); function func1() { console.log('First output'); } function func2() { console.log('Output from second'); } function func3() { console.log('Yet a third output'); }
 <button>Run a random function!</button>

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

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