我需要帮助在JS中编写这个IF语句

时间:2017-07-26 05:03:01

标签: javascript if-statement

我有一个游戏,您可以在每次转弯时将分数输入到输入框中。我写了一个for循环来添加每个回合的总数并将其显示在“总得分”框中。但是在这个游戏中,如果你所有回合结束时的“总得分”大于或等于50,你将获得10点奖励。

所以我创建了另一个名为“Total”的输入框。我想创建一个IF语句,以便如果“总分数”输入框中的数字大于或等于50,则您的分数加上10分奖励将显示在其下方的“总计”框中。我怎么能这样做?

这是我的代码:

//input form   

Turn 1: <input onblur="findTotal()" type="text" name="qty">
<br>
Turn 2: <input onblur="findTotal()" type="text" name="qty">
<br>
Trun 3: <input onblur="findTotal()" type="text" name="qty">
<br>
<b>Total Score:</b> <input type="text" name="TotalScore" id="TotalScore">
<br>
Bonus (+10): <input type="text" name="bonus">
<br>
<b>Total:</b> <input type="text" name="Total">

//for loop

function findTotal() {
    var arr = document.getElementsByName('qty');
    var tot = 0;
    for (var i = 0; i < arr.length; i++) {
        if (parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('Total').value = tot;
}
onblur = "findTotal()"

//my attempt at the IF statement ("alert hello" is just a place holder)

var tots = document.getElementById('TotalScore');

if (tots.value >= 50) {
    alert("hello");
}

2 个答案:

答案 0 :(得分:1)

您可以尝试检查用户是否在findTotal功能结束时获得了奖励(您无论如何只计算了total score):

&#13;
&#13;
function findTotal() {
  var arr = document.getElementsByName('qty');
  var tot = 0;
  for (var i = 0; i < arr.length; i++) {
    if (parseInt(arr[i].value))
      tot += parseInt(arr[i].value);
  }

  document.getElementById('TotalScore').value = tot;

  var bonus = tot >= 50 ? 10 : '';
  document.getElementById('bonus').value = bonus;
  document.getElementById('Total').value = tot + bonus;
}
&#13;
Turn 1: <input onblur="findTotal()" type="text" name="qty">
<br> Turn 2: <input onblur="findTotal()" type="text" name="qty">
<br> Turn 3: <input onblur="findTotal()" type="text" name="qty">
<br>
<b>Total Score: </b> <input disabled="true" type="text" name="TotalScore" id="TotalScore">
<br> Bonus: <input disabled="true" type="text" id="bonus">
<br>
<b>Total:</b> <input disabled="true" type="text" id="Total">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

提供文本框ID,

<b>Total:</b> <input type="text" id="tots" name="Total">

并使用if as,

 if($('#tots').value>=50){}
相关问题