Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

logic - Create multiple Buttons with ClickListener and identify what Button was clicked? (JavaScript)

Think of the Uno Card Game logic for example, how could I get the clicked Card on the players hand, when I create the cards on the players hand dynamically by clicking on a draw button?

something like:

var btn = document.createElement("BUTTON");
btn.onclick = () => {
  alert(btnCounter);
}
btnCounter++;

but the onclick function should be written once and then be saved for this button.

question from:https://stackoverflow.com/questions/65546352/create-multiple-buttons-with-clicklistener-and-identify-what-button-was-clicked

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option is to rely on event bubbling. We can add the event listener to the container for our hand and then, on click, make sure the clicked element was a button. In this example, I put our card's value in the button's dataset, but you can grab the info from anywhere on the target.

const hand = document.querySelector("#hand");

hand.addEventListener("click", function(e) {
  if (e.target.tagName !== "BUTTON") return;
  console.log(e.target.dataset.card);
});

function drawCards(numberOfCards) {
  for (let i = 0; i < numberOfCards; i++) {
    const button = document.createElement("button");
    const card = Math.floor(Math.random() * 10);
    button.setAttribute("data-card", card);
    button.innerHTML = card;
    hand.appendChild(button);
  }
};

drawCards(5);
<div id="hand"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...