简体   繁体   English

addEventListener 点击事件不起作用

[英]addEventListener click event is not working

I am doing a project on paper-rock-scissor that has UI.我正在做一个有 UI 的剪纸剪刀项目。 So, I have four buttons, Start game, rock, paper and scissor .所以,我有四个按钮,开始游戏,石头,纸剪刀 Previously I write the code separately and it works.以前我单独编写代码并且它可以工作。 But right now because I want the result from clicking the button to be an input to another function.但是现在因为我希望单击按钮的结果成为另一个函数的输入。 So I tried to group all the buttons altogether in my code below.因此,我尝试在下面的代码中将所有按钮完全分组。 However, it seems like the button doesnt seem to work but there are no errors.但是,似乎该按钮似乎不起作用,但没有错误。 I have no idea why?我不知道为什么? Below are my code :下面是我的代码:

------------- HTML --------------- ------------- HTML ---------------

<!DOCTYPE html>

<html lang="en">
    
    <head>
        <meta charset="utf-8">
        <title>Project Rock Paper Scissors</title>
        <script src = "javascript.js" defer> </script>
    </head>

    <body>
        <div class="btn-group">
            <button id="startgame"> Start game </button>
            <button id="rock"> Rock </button>
            <button id="paper"> Paper </button>
            <button id="scissor"> Scissor </button>
        </div>
        
        
    </body>

</html>

------------ Javascript --------------- ------------ Javascript ---------------

const button = document.querySelector(".btn-group");
const startGame = document.querySelector('#startgame');
const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissor = document.querySelector('#scissor');

 button.addEventListener('click', function(selection) {
        if (selection === startGame) {
            startGame.addEventListener('click', () => {
            alert("Choose Rock, Paper or Scissor");
            })
        }  else if (selection === rock) {
             rock.addEventListener('click', () => {
                let item = "rock";
                return item.toLowerCase();
            })
        }  else if (selection === paper) {
            paper.addEventListener('click', () => {
                let item2 = "paper";
                return item2.toLowerCase();
            })
        } else if (selection === scissor) {
            scissor.addEventListener('click', () => {
                let item3 = "scissor";
                return item3.toLowerCase();
            })
            }            
    })

----------- Js code above to be used as argument to function playRound(.... , ....) below ------------ ------------ 上面的 Js 代码用作下面的函数 playRound(.... , ....) 的参数 ------------

function playRound(playerSelection, computerSelection)  {
        if (playerSelection === "Paper".toLowerCase()  && computerSelection.toLowerCase()  === "Rock".toLowerCase() )  {
            console.log(`Player choose ${playerSelection} and computer plays ${computerSelection} player wins !`);
        } else if (playerSelection  === "Scissor".toLowerCase()  && computerSelection.toLowerCase() === "Paper".toLowerCase() ) {
            console.log(`Player choose ${playerSelection} and computer plays ${computerSelection} player wins !`);
        }  else if (playerSelection  === "Rock".toLowerCase()  && computerSelection.toLowerCase() === "Scissor".toLowerCase() ) {
            console.log(`Player choose ${playerSelection} and computer plays ${computerSelection} player wins !`);
        }  else if (playerSelection  ===  computerSelection.toLowerCase()  ) {
            console.log(`Player choose ${playerSelection} and computer plays ${computerSelection} game is draw !`);
        } else {
            console.log(`Player choose ${playerSelection}, computer plays ${computerSelection}, computer wins !`);
    }
}

you have a bug in your code where selection is an event object, and not the element which generated the event:您的代码中有一个错误,其中selection是一个事件对象,而不是生成事件的元素:

 button.addEventListener('click', function(selection) { ...

Your if statements are comparing selection (the event object) to strongly equal the elements that were clicked, which is where it is getting skipped.您的if语句将selection (事件对象)与被单击的元素进行比较,这就是它被跳过的地方。 On the event object selection you'll find the target property: see https://developer.mozilla.org/en-US/docs/Web/API/Event/target在事件对象selection ,您将找到target属性:请参阅https://developer.mozilla.org/en-US/docs/Web/API/Event/target

So you might write your if statments this way:所以你可以这样写你的 if 语句:

if ( selection.target == startgame ) { ....

Finally, the event listener is on the outer div and not on each button themselves.最后,事件侦听器位于外部 div 上,而不是每个按钮本身。

There are a few of issues there:那里有几个问题:

  1. You're waiting until a click occurs anywhere within .btn-group before you add click handlers to the buttons themselves.在将单击处理程序添加到按钮本身之前,您要等到.btn-group中的任何位置发生单击。 That doesn't make any sense.这没有任何意义。 You would either use an overall click handler on .btn-group and use event delegation to determine what button was pressed, or use event handlers on the individual buttons (probably simpler in this specific case).可以.btn-group上使用整体单击处理程序并使用事件委托来确定按下了哪个按钮,或者在各个按钮上使用事件处理程序(在这种特定情况下可能更简单)。

  2. An event handler receives an event object , not an element, so selection will never match startgame or any of the others.事件处理程序接收事件对象,而不是元素,因此selection永远不会匹配startgame或任何其他。 The event object's target property refers to the element where the event was targeted, so with your markup that would match one of your buttons (but beware that if you had <button><strong>xyz</strong></button> , it would be the strong element, not the button element, so you'd have to handle that, perhaps with closest ).事件对象的target属性是指事件所针对的元素,因此您的标记将匹配您的按钮之一(但请注意,如果您有<button><strong>xyz</strong></button> ,它将是strong元素,而不是button元素,所以你必须处理它,也许用closest )。

  3. You're returning item.toString() from your inner event handlers, but that doesn't do anything useful.您正在从内部事件处理程序返回item.toString() ,但这并没有做任何有用的事情。 The return value from an addEventListener event handler is completely ignored. addEventListener事件处理程序的返回值被完全忽略。

The simple way to fix #1 and #2 is (in this case) to remove the .btn-group handler entirely and just hook up the buttons directly.修复 #1 和 #2 的简单方法是(在这种情况下)完全删除.btn-group处理程序并直接连接按钮。 To fix #3, you have to provide yourself some way of showing that information in the DOM.要修复 #3,您必须为自己提供一些在 DOM 中显示该信息的方法。 There are dozens of ways of doing that, so I won't go into specifics here, but you can't just return it and have anything useful happen.有很多方法可以做到这一点,所以我不会在这里详细说明,但你不能只是退回它并让任何有用的事情发生。

If you want to add events when .btn-group is clicked:如果要在单击.btn-group时添加事件:

const button = document.querySelector(".btn-group");
const startGame = document.querySelector('#startgame');
const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissor = document.querySelector('#scissor');

function addEvents(){
    startGame.addEventListener('click', () => {
        alert("Choose Rock, Paper or Scissor");
    })
     rock.addEventListener('click', () => {
        let item = "rock";
        return item.toLowerCase();
    })
    paper.addEventListener('click', () => {
        let item2 = "paper";
        return item2.toLowerCase();
    })
    scissor.addEventListener('click', () => {
        let item3 = "scissor";
        return item3.toLowerCase();
    })
}

button.addEventListener('click', addEvents)

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

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