简体   繁体   中英

Is there anyway to shorten this javascript code?

I am a Javascript beginner, I am trying to make the rock paper scissor game as a beginner practice project. I wrote a piece of code to assign the move of the player. I have three buttons on the page for the respektive moves

如图所示

Here is the code that i wrote to assign the value to the variable of Player move-

const paper =document.getElementById('paper');
const scissor = document.getElementById('scissor')
const rock = document.getElementById('rock')

paper.addEventListener('click', function (){movePlayer = "paper"; })
rock.addEventListener('click', function (){movePlayer = "rock"; })
scissor.addEventListener('click', function (){movePlayer = "scissor";})

The ID rock, paper, scissor are for the respective buttons.

I feel that there is a shorter way to do this. This my first time on Stack Overflow

SO normally does not do code review. But here you are

['paper','scissor','rock'].forEach(hand => document.getElementById(hand) 
  .addEventListener('click', function() { movePlayer = this.id }));

but why not delegate?

 let movePlayer; const showMove = () => console.log(movePlayer); document.getElementById("handContainer").addEventListener('click', function(e) { const tgt = e.target; if (tgt.classList.contains("hand")) { movePlayer = tgt.id; showMove(); } });
 <div id="handContainer"> <div class="hand" id="paper">Paper</div> <div class="hand" id="scissors">Scissors</div> <div class="hand" id="rock">Rock</div> <div class="hand" id="lizard">Lizard</div> <div class="hand" id="spock">Spock</div> </div>

You can use an array and a loop:

for (const type of ["rock", "paper", "scissor"]) {
    document.getElementById(type).addEventListener("click", () => {
        movePlayer = type;
    });
}

Or forEach , which is also a loop, just a less obvious one.


Side note: It's usually "scissors" rather than "scissor."

You can listen to your div elements click event. then in your click function get the element id and set movePlayer like this:

 document.querySelectorAll('div').forEach((div) => { div.addEventListener('click', function() { movePlayer = this.id }) })

Edit: You can assign a class to your elements and use document.querySelectorAll('.classname') either

Using event delegation springs to mind

document.addEventListener("click", evt => {
  const origin = evt.target.closest("#rock, #paper, #scissor");
  if (origin) { movePlayer = origin.id; }
});

Demo :

 document.addEventListener("click", evt => { const origin = evt.target.closest("#rock, #paper, #scissor"); if (origin) { movePlayer = origin.id; // for demo const picked = document.querySelector(".picked"); const movePlayerId = document.querySelector(".movePlayer"); picked && picked.classList.remove("picked"); movePlayerId && movePlayerId.classList.remove("movePlayer"); origin.firstChild.classList.add("picked"); origin.classList.add("movePlayer"); } });
 div { cursor: pointer; margin: 5px; } .picked { border-color: red; } div.movePlayer:after { content: ' > movePlayer now: 'attr(id); color: green; } span { padding: 3px; border: 1px solid transparent; }
 <div id="paper"><span>Paper</span></div> <div id="scissor"><span>Scissor</span></div> <div id="rock"><span>Rock</span></div>

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