如果条件在回调函数内不起作用

时间:2018-04-18 17:41:00

标签: javascript dom

如果我这样写,事情就会起作用

var p1Button = document.getElementById("p1Button");
var p1Score = 0;
var p1Span = document.getElementById("p1ScoreSpan");

var p2Button = document.getElementById("p2Button");
var p2Score = 0;
var p2Span = document.getElementById("p2ScoreSpan");

var winningScore = document.querySelector("#targetScore").textContent
var gameOver = false;

//for the reset button
var resetButton = document.getElementById("ResetButton");

p1Button.addEventListener("click", function(){
    // console.log(gameOver)
    if(!gameOver) {
        p1Score++;
        if(p1Score == winningScore) {
            p1Span.classList.add('winner');
            gameOver = true;
        }
        p1Span.textContent = p1Score;
    }

})


p2Button.addEventListener("click", function () {
    console.log(gameOver)
    if (!gameOver) {
        p2Score++;
        if(p2Score == winningScore){
            p2Span.classList.add('winner');
            gameOver = true;
        }}
        p2Span.textContent = p2Score;
})

但要保持'DRY'创建一个函数并将其用作回调似乎不起作用。下面是代码片段,即使没有单击HTML

中定义的“按钮”,它也可以运行
var callBackfunct = function (playerScore, playerSpan) {
    console.log(gameOver)
    console.log(winningScore)
    if (!gameOver) {
        playerScore++;
        if (playerScore == winningScore) {
            playerSpan.classList.add('winner');
            gameOver = true;
        }
    }
    playerSpan.textContent = playerScore;
    console.log(gameOver)
}

p1Button.addEventListener("click", callBackfunct(p1Score, p1Span));

p2Button.addEventListener("click", callBackfunct(p2Score, p2Span));

我错在哪里?我期待当我点击播放器1按钮时,通过调整if条件来调用回调函数

2 个答案:

答案 0 :(得分:2)

你正在立即调用该函数添加箭头功能,它应该可以正常工作

p2Button.addEventListener("click", () => callBackfunct(p2Score, p2Span));

或非ES6

p2Button.addEventListener("click", function() {
   callBackfunct(p2Score, p2Span)
});
  

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

     

可以将事件侦听器指定为回调函数或实现EventListener的对象,其handleEvent()方法用作回调函数。

答案 1 :(得分:1)

Instead of calling the function directly:

 callBackfunct(p1Score, p1Span)

Just create a bound function which you can then pass to the handler, so that the handler can call it later:

 callBackfunct.bind(null, p1Score, p1Span)