为什么您的功能youWin无法正常工作?

时间:2018-10-16 17:55:03

标签: javascript function comparison-operators

我相信我会在此处发布所有相关代码。

该功能确实可以运行,因为如果我将>切换为<,则在单击'moveup'按钮时会发出警报。
另外,控制台记录到pic2继续以每个增量增长,而pic3保持不变。因此,该部分正在工作。

该函数中的某些内容无法正确比较这两个变量,并且我无法弄清楚出了什么问题。

var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;

console.log(player);
console.log(finish);

function youWin() {
  if (player >= finish) {
    alert("You Win!");
  } else {

  }
};

$(function() {
  $('#moveup').click(function() {
    $("#pic2").css('margin-left', '+=2vw');
    $("#pic3").css('margin-left', '-=2vw');
    document.getElementById("guessField").value = "";
    $('#myModalTrue').toggle();
    y = regenerate();
    var player = document.getElementById("pic2").offsetLeft;
    var finish = document.getElementById("pic3").offsetLeft;
    console.log(player);
    console.log(finish);
    youWin();
  });
});

2 个答案:

答案 0 :(得分:1)

您没有更改全局playerfinish变量。您正在制作新的本地商品。有关variable scope in javascript的更多信息。试试这个

var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;

console.log(player);
console.log(finish);

function youWin() {
  if (player >= finish) {
    alert("You Win!");
  } else {

  }
};
$(function() {
  $('#moveup').click(function() {
    $("#pic2").css('margin-left', '+=2vw');
    $("#pic3").css('margin-left', '-=2vw');
    document.getElementById("guessField").value = "";
    $('#myModalTrue').toggle();
    y = regenerate();
    player = document.getElementById("pic2").offsetLeft;//change is here
    finish = document.getElementById("pic3").offsetLeft;//and here
    console.log(player);
    console.log(finish);
    youWin();
  });
});

答案 1 :(得分:0)

尝试在youWin函数中记录值,它应该返回旧值和您的答案。您的playerfinish的值未针对功能进行更新。它仍然在变老的价值。

function youWin(player, finish) {
  if (player >= finish) {
    alert("You Win!");
  } else {

  }
};

$(function() {
  $('#moveup').click(function() {
    $("#pic2").css('margin-left', '+=2vw');
    $("#pic3").css('margin-left', '-=2vw');
    document.getElementById("guessField").value = "";
    $('#myModalTrue').toggle();
    y = regenerate();
    var player = document.getElementById("pic2").offsetLeft;
    var finish = document.getElementById("pic3").offsetLeft;
    console.log(player);
    console.log(finish);
    youWin(player, finish);
  });
});