如何确认提示值,然后将1添加到变量

时间:2016-01-30 15:32:36

标签: javascript jquery

var button = (".button");
var password = "rip peter";
var jimmyCount = 0;
var nickCount = 0;  

$( ".button" ).click(function() {
    var userAnswer = prompt("Who would win in a fight\n\nJimmy or Nick?", "");
    console.log(userAnswer);
});

    // Compare

var compare = function(userAnswer, password) {
    if (userAnswer != password) {
        alert("Nope");
    }
    else {
        $("#jimmyMinus").click(function() { jimmyCount -= 1});
        $("#jimmyPlus").click(function() { jimmyCount += 1});
        $("#nickMinus").click(function() { nickCount -= 1});
        $("#nickPlus").click(function() { nickCount += 1});
    }
}

我正在尝试构建一个需要“密码”的计数器,以允许用户+1或-1来获得分数。但是,当提示有效时,并存储该值,它不会被比较也不会添加/减去..

此外,我想将此号码添加到某处的html,但不知道如何:s

1 个答案:

答案 0 :(得分:0)

您没有执行compare()功能:

$( ".button" ).click(function() {
  var userAnswer = prompt("Who would win in a fight\n\nJimmy or Nick?", "");
  console.log(userAnswer);
  compare(userAnswer);
});

此外,在声明函数后抛出上面的处理程序。

var button = (".button");
var password = "rip peter";
var jimmyCount = 0;
var nickCount = 0;  

// Compare

var compare = function(userAnswer) {
  if (userAnswer != password) {
    alert("Nope");
  }
  else {
    $("#jimmyMinus").click(function() { jimmyCount -= 1});
    $("#jimmyPlus").click(function() { jimmyCount += 1});
    $("#nickMinus").click(function() { nickCount -= 1});
    $("#nickPlus").click(function() { nickCount += 1});
  }
}

$( ".button" ).click(function() {
  var userAnswer = prompt("Who would win in a fight\n\nJimmy or Nick?", "");
  console.log(userAnswer);
  compare(userAnswer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="button">Click Me</span>

从函数中删除password的第二个参数。