如何停止eventListener并重新激活它

时间:2018-03-27 08:07:03

标签: javascript jquery

伙计我有这个代码

var clicks = 0;
$('.card').on('click', function(){
    if(cardOpend === 5){
        //SOME CODE

    }else{
        clicks++;
        if(clicks === 2){
            $('.card').off('click');
        }
    }
    setTimeOut(function(){
        $('.card').on('click');
    }, 1000);
});

但不幸的是,这不起作用

我想让事件监听器暂停一秒钟,然后让它恢复工作。

更多详情

我正在尝试建立记忆卡游戏 如果玩家点击第一张牌,它将打开,然后是下一张牌 如果没有匹配停止点击事件,以防止玩家点击其他卡,而功能显示玩家没有匹配,然后当卡翻转时,事件重新激活并重新开始工作。

function shuffle(array) {

    'use strict';

    var currentIndex = array.length, temporaryValue, randomIndex;

    while (currentIndex !== 0) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}
//ALL VARIABLES
const DOMString = {
    container: $('.deck'),
    card: '.card',
    cardOpend: [],
    gameIsStarted: false,
    matches: 0,
    moves: 0
};

const cards = ['fa-diamond', 'fa-paper-plane-o', 'fa-anchor', 'fa-bolt', 'fa-cube', 'fa-anchor', 'fa-leaf', 'fa-bicycle', 'fa-diamond', 'fa-bomb', 'fa-leaf', 'fa-bomb', 'fa-bolt', 'fa-bicycle', 'fa-paper-plane-o', 'fa-cube'];


//FUNCTIONS
function creatUI(){
    let cardsShuffel = shuffle(cards);
    cardsShuffel.forEach((cur) => {
        DOMString.container.append('<li class="card"><i class="fa ' + cur + '"></i></li>');
    });
}

function startGame(){
    //flip Card when user click
    $(DOMString.card).on('click', function(){
        //ADD Calsses
        $(this).toggleClass('flipInY open show');
        //push the opend card into the Array
        DOMString.cardOpend.push($(this));
        //Start The game
        DOMString.gameIsStarted = true;
        //Check if there are a match
        if(DOMString.cardOpend.length === 2){
            if(DOMString.cardOpend[0][0].firstChild.classList[1] === DOMString.cardOpend[1][0].firstChild.classList[1]){
                DOMString.cardOpend[0][0].classList.add('match');
                DOMString.cardOpend[1][0].classList.add('match');

                //clear cardOpend array
                DOMString.cardOpend = [];

                //Increase Matches
                DOMString.matches++;

                //Increase Moves
                DOMString.moves++;
            }else{
                //add wrong class to opend cards
                DOMString.cardOpend[0][0].classList.add('wrong');
                DOMString.cardOpend[1][0].classList.add('wrong');

                //reclose all opend cards
                setTimeout(function(){
                    $(DOMString.card).removeClass('open show wrong');
                    $(DOMString.card).removeClass('open show wrong');

                    //set cardOpend array to empty
                    DOMString.cardOpend = [];
                }, 1000);

                //Increase Moves
                DOMString.moves++;
            }
        }
    });
}


//CALL FUNCTIONS
creatUI();
startGame();

2 个答案:

答案 0 :(得分:0)

这里的问题是public void display() { super.display(); } 不是一个函数,要重新激活它,你必须传递给$('.card').on('click')一个函数,如下所示:

setTimeout

修改

但是,如果您在动画期间尝试阻止对元素的单击,则可以使用var clicks = 0; var onClickFunction = function(){ if(cardOpend === 5){ //SOME CODE }else{ clicks++; if(clicks === 2){ $('.card').off('click'); } } setTimeOut(function() { $('.card').off('click', onClickFunction); // Avoid multiple listeners $('.card').on('click', onClickFunction); }, 1000); }; $('.card').on('click', onClickFunction); event.preventDefault检查类以防止动画期间的单击事件。< / p>

event.stopPropagation

答案 1 :(得分:0)

卡片翻转,没有癌症的东西:

let clicks = 0;
const cards = document.querySelectorAll(".card");
let addHandler;
const delay = x => new Promise(res => setTimeout(res, x));
const handler = e => {
  if (clicks == -1) // Blocked
    return;

  const card = e.target;
  card.classList.toggle("flipped");
  if (false /* placeholder */ ) {
    //SOME CODE
  } else {
    clicks++;
    if (clicks == 2) {
      clicks = -1; // Block further clicks

      card.addEventListener("transitionend", async() => {
        // Reset after 1s
        await delay(1000);

        clicks = 0;
        cards.forEach(c => {
          c.classList.remove("flipped");
          c.removeEventListener("click", handler);
        });
        cards.forEach(addHandler);
      }, {
        once: true
      });
    }
  }
}
addHandler = card => card.addEventListener("click", handler, {
  once: true
});
cards.forEach(addHandler);
.card {
  transition: all linear 0.5s;
  will-change: transform;
}

.card.flipped {
  transform: scaleX(-1);
}
<button class="card">Card 1</button>
<button class="card">Card 2</button>
<button class="card">Card 3</button>
<button class="card">Card 4</button>