总结HTML,jQuery和Javascript

时间:2014-07-19 04:18:31

标签: javascript jquery html

我想在文本框中添加用户输入的值,并通过名为“sum”的变量进行打印。 输入的值被赋予相同的变量,即x的第一时间值是4,下次用户输入x = 5的值;那么总和应该是4 + 5 = 9 但是输出是45,即它保持打印值彼此相邻。 有什么办法,我可以打印我想要的输出。 我的代码随附于此。

”                                     

</script>

</head>
 <body>
<div id="header">
<h1 style="margin-bottom:0;"><center><img src="ccc.jpg" /></center></h1>
</div>
<div id="menu" style="background-color:white ;height:500px;width:150px;float:left;">


</div>
<h3>
<center>
<form>
<fieldset>
    <legend>It's Cricket Time - Score as many runs as possible</legend>
    <label>Enter Your Number</label>
    <input type =" number" name="number" id= "test1" />
    <input type ="button" id= "tab1" value="Click Me" onclick= "out()" />    
    <br>
    <label>Your Score:</label>
    <h5 id ="output"></h5>
 </fieldset>
</form>

<br>
</center></h3>
<script>
var sum=0;
function out()
 {

    var x= $("#test1").val();
    var array=[0,1,2,4,6,0,1,2,4,6,0,1,2,4,6,0,1,2,4,6];

    var y = Math.floor((Math.random() * 20));

    //if( x !==0 || x !==1 || x !==2 || x !==4 || x !==6 )
    //{
    //  document.getElementById("output").innerHTML="Enter a legitimate number!!";
    //  window.setTimeout("location.reload()", 500);
    //}

    //else
    {       

        if(x == array[y] )
            {   
                document.getElementById("output").innerHTML="YOU ARE OUT";
            }
        else
            {
                sum=sum+x;
                document.getElementById("output").innerHTML=sum;

            }
    document.getElementById("test1").value='';
   //   document.getElementById("output").innerHTML=sum;
        console.log(array[y]);
}

    }


  </script>
 <div id="footer" style="background-color:#0099FF;clear:both;text-align:center;">
            Copyright © rooparshkalia productions</div>
 </body>
   </html>   '

3 个答案:

答案 0 :(得分:0)

您的值被视为string数据类型。它们需要被视为int数据类型。 Javascript是一种动态语言,在运行时推断出类型。

document.getElementById("test1").value=''更改为document.getElementById("test1").value=0

我没有查看你的代码,但是如果这不起作用,那么使用基数为10的基数的parseInt

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

parseInt(string,10)

答案 1 :(得分:0)

当您编写sum = sum + x;时,它会将sumx连接为字符串。试试这个,如果这段代码有效,请告诉我。

else
{
    sum = sum + parseInt(x); // or sum += parseInt(x);
    document.getElementById("output").innerHTML = sum;
}

答案 2 :(得分:0)

使用Jquery parseInt 函数将字符串解析为int。

    var sum = 0;
    function out() {

        var x = $("#test1").val();
        var array = [0, 1, 2, 4, 6, 0, 1, 2, 4, 6, 0, 1, 2, 4, 6, 0, 1, 2, 4, 6];

        var y = Math.floor((Math.random() * 20));
        if (x == array[y]) {
            document.getElementById("output").innerHTML = "YOU ARE OUT";
        }
        else {
            sum = parseInt(sum) + parseInt(x);
            document.getElementById("output").innerHTML = sum;

        }
        document.getElementById("test1").value = '';
        console.log(array[y]);
    }