简体   繁体   English

Function 内部事件监听器不会运行

[英]Function inside event listener won't run

How do I get the function computerChoice() to run when I click on the strawberryButton which has an addEventListener?当我单击具有 addEventListener 的strawberryButton按钮时,如何让function computerChoice()运行? At the moment nothing happens when I click on strawberryButton目前,当我单击strawberryButton按钮时,什么也没有发生

<div class="fruits"> 
    <div class="strawberry">
        <img class="strawberry-button" src="strawberry1.png" height=250px></div>
    <div class="orange">
        <img class="orange-button" src="orange.png" height=250px width=250px></div>
    <div class="pineapple">
        <img class="pineapple-button" src="pineapple.png" height=250px width=250px></div>
    <div class="pear">
        <img class="pear-button" src="pear.png" height=250px width=250px></div>
</div>

my JS我的 JS

// Initialize everything to zero
let score = 0;
let rounds = 0;

const strawberryButton = document.querySelector(".strawberry-button");
const orangeButton = document.querySelector(".orange-button");
const pearButton = document.querySelector(".pear-button");
const pineappleButton = document.querySelector(".pineapple-button");
const score_div = document.querySelector(".score");
const userChoice_div = document.querySelector(".user-choice");
const computerChoice_div = document.querySelector(".computer-choice");

    function computerChoice(){
        const fruitSelection = ["orange", "strawberry", "pear", "pineapple"];
        const pickFruit = fruitSelection[Math.floor(Math.random() * 4)];
        return pickFruit;

    }

strawberryButton.addEventListener('click', computerChoice)

The click handler is called.调用点击处理程序。 You can verify this by using a simple console output in the method:您可以通过在方法中使用简单的控制台 output 来验证这一点:

function computerChoice(){
  console.log("click")
  // etc

I assume you want to process the value from the method, but you return it to nowhere.我假设您想处理方法中的值,但您将它返回到无处。

You could define another variable below rounds , like this:您可以在下面定义另一个变量rounds ,如下所示:

let pickedFruit = null

And then you assign the value in the click handler.然后在单击处理程序中分配值。

pickedFruit = fruitSelection[Math.floor(Math.random() * 4)];

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

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