缩短代码的想法,代码运行良好,但必须用for循环缩短它

时间:2017-04-11 17:33:03

标签: javascript jquery

正如你看到的工作代码我上传了一个链接但是我需要为LOOP创建因为目前我在一个数组中只有3个项目我有一个代码可以将每个点击添加到一个项目中未命名:那个'为什么我需要你的朋友。有人有一个想法,我在这里寻找LOOP,但有我已经知道的信息我需要一个LOOP,创建一个VAR类似var val [i] = $("#singel" [i]) ; https://jsfiddle.net/iandslevi/6uew8fqu/1/

<html>
    <head>
        <title>Page Title</title>
        <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
        <style type="text/css">

            #singels{
                background-color: #bfbfbf;
                color: #ffff33;
                text-align: center;
                width: 100%;

            }

        </style>
    </head>

<body>




            <div id="singels">
                <form action="index.php" method="post"><ul style="list-style-type: none;"></ul><input type="submit" value="Place Bet" name="submit"></form>
            </div>



        <script type="text/javascript">
$( document ).ready(function (){
var singelsvalue = ["2","3","4"];
var singel = ["test1","test2","test3"];

if (singelsvalue.length !== 0)
{
    // var someSingel = "0";
    if(someSingel = "undefinted"){someSingel = "0"}
    if(someSingel1 = "undefinted"){someSingel1 = "0"}

        $(document).ready(function()
        {

            $("#singel0").keyup( function(){
            var val0 = $("#singel0").val();
            var someSingel0 = val0 * singelsvalue[0];
            $("#span0").text(someSingel0.toFixed(2));
            someSingel0 = someSingel0 * val0;
            });

                $("#singel1").keyup( function(){
                var val1 = $("#singel1").val();
                var someSingel1 = val1 * singelsvalue[1];
                $("#span1").text(someSingel1.toFixed(2));
                someSingel1 = someSingel1 * val1;
                });

                    $("#singel2").keyup( function(){
                    var val2 = $("#singel2").val();
                    var someSingel2 = val2 * singelsvalue[2];
                    $("#span2").text(someSingel2.toFixed(2));
                    someSingel2 = someSingel2 * val2;
                    });                    
        });



        for(i=0; i<singel.length ; i++)
        {
            var someSingel = someSingel[i];
            if(someSingel = "undefinted"){someSingel = "0"}
            $("#singels form ul").append("<li>"+ singel[i] + " " + singelsvalue[i]+  " x " +'<input id="singel'+i+'" name="singel" type="text" placeholder="stake"><p>To Return :<span id="span'+i+'">'+ someSingel +'<span></p></li>');
        }


}
});

</script>



 </body>
</html> 

0 个答案:

没有答案