如何在函数中创建GLOBAL变量

时间:2017-04-13 17:19:42

标签: javascript jquery html

我无法理解为什么?在我输入一位数后,它就可以了。当我插入两位或三位数字时,它只会打印几行。我知道这与你点击KEYUP的次数有关。我在这里寻找有关GLOBAL VAR的信息,但我不太明白。我知道当我在函数外创建一个对象时。这应该工作。但是当我尝试它时,他只是没有给它。我附上了一个链接链接。感谢所有试图检查的人:)

https://jsfiddle.net/iandslevi/0q651xw8/6/

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">    </script>
<title>Page Title</title>
</head>

<body>
  <div id="singels">
    <form id="form" method="post">
      <ul style="list-style-type: none;">
        <li>team A -> 5  x <input id="singel" name="singel" type="text" placeholder="stake">
          <p>To Return :</p><span id="span"></span></li>
      </ul><input type="submit" value="Place Bet" name="submit"></form>
  </div>

  <div id="res">
  </div>

<script>
$(document).ready(function ()
{
var team = ["team A"];
var valueOfTeam = ["5"];

  $("#singel").keyup( function()
  {
     var val = $("#singel").val();
     var someSingel = val * valueOfTeam[0];
     var singeltest = team[0];
     $("#span").text(someSingel.toFixed(2));
     someSingel = someSingel * val;

     $("#form").submit(function ()
     {
       $("#res").append(singeltest+"  "+
       (valueOfTeam[0]*val)+"</br>");
       return false;
      });
   });
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:-1)

这应该可以解决问题:

&#13;
&#13;
$(document).ready(function (){
    var team = ["team A"];
    var valueOfTeam = ["5"];
    var singeltest = team[0];
    var val = 0;
    
    $("#submit").click(function () {
        $("#res").append(singeltest + "  " + (valueOfTeam[0]*val)+"</br>");
        return false;
    });
        
    $("#singel").keyup( function() {
        val = $("#singel").val();
        var someSingel = val * valueOfTeam[0];
        singeltest = team[0];
        $("#span").text(someSingel.toFixed(2));
        someSingel = someSingel * val;
    });
});
&#13;
<div id="singels">
     <form id="form" method="post">
        <ul style="list-style-type: none;">
            <li>team A -> 5 x
                <input id="singel" name="singel" type="text" placeholder="stake">
                <p>To Return :</p><span id="span"></span>
            </li>
        </ul>
        <input type="button" value="Place Bet" id="submit">
    </form>
</div>    
<div id="res"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

使用JSFiddle:https://jsfiddle.net/apytypgf/1/