问题描述:

I'm working on a card game where the user has to select a card from a set of 4. If it is an Ace then they win if not then they lose. But I'm having some trouble removing the event listener of click from the set of cards after the first card has been clicked.

for(var i = 0; i < card.length; i++)

{

card[i].addEventListener("click",display);

}

function display()

{

this.setAttribute("src","CardImages/" + deck[this.id] + ".jpg");

this.setAttribute("class","highlight");

if(firstGo == 0)

{

firstGo++;

firstCard = this;

this.removeEventListener("click",display);

console.log("card" + deck[this.id]);

}

else

{

alert("You've already selected a card");

this.removeEventListener("click",display);

}

}

网友答案:

You are adding click events using a loop because you have multiple cards.

for(var i = 0; i < card.length; i++) {
    card[i].addEventListener("click", display);
}

but you're removing the event listeners using

this.removeEventListener("click",display);

which will only remove the listener on the card you clicked. If you want to remove the listener on other cards too, you should also remove them in a loop.

function display() {
    this.setAttribute("src","CardImages/" + deck[this.id] + ".jpg");
    this.setAttribute("class","highlight");
    if (firstGo == 0) {
        firstGo++;
        firstCard = this;
        // this.removeEventListener("click",display);
        for (var i = 0; i < card.length; i++) {
            card[i].removeEventListener("click", display);
        }
        console.log("card" + deck[this.id]);
    } else {
        alert("You've already selected a card");
        // this.removeEventListener("click",display);
        for (var i = 0; i < card.length; i++) {
            card[i].removeEventListener("click", display);
        }
    }
}

Here's a working demo.

var cards = document.getElementsByClassName("card");

for (var i = 0; i < cards.length; i++) {
  cards[i].addEventListener("click", display);
}

function display() {
  this.classList.add("highlight");
  for (var i = 0; i < cards.length; i++) {
    cards[i].removeEventListener("click", display);
  }
}
.card {
  float: left;
  padding: 50px 40px;
  border: 1px solid rgba(0,0,0,.2);
  margin: 5px;
  background: white;
}
.card:hover {
  border: 1px solid rgba(0,0,255,.4);
}
.card.highlight {
  border: 1px solid rgba(0,200,0,.5);
}
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
网友答案:

I'm not sure what your card array looks like, but I filled in the rest on a codepen and it seems to be successfully removing the eventListener. Is your card array referencing specific DOM elements like this for example?

var a = document.getElementById('A');
var b = document.getElementById('B');
var c = document.getElementById('C');
var card = [a, b, c];
相关阅读:
Top