【问题标题】:How to use loop for on javascript and use var in loop for?如何在javascript上使用循环并在循环中使用var?
【发布时间】:2015-07-01 11:40:44
【问题描述】:

如何在 javascript 上使用循环 for 并在循环中使用 var for ?

点击按钮时。使用loop for输入类型文本将是自动填充值

但不工作,我该怎么做?

http://jsfiddle.net/fNPvf/16471/

function change(){    
    var price_start = document.getElementById('price_start').value;
    for (i = 1; i <= 14; i++) { 
        constance_val = i*2;
        price_month_+i+ = price_start*constance_val;
        document.getElementById('price_month_'+i+).value = price_month_+i+; 
    }
}

【问题讨论】:

标签: javascript


【解决方案1】:

您不能将i+ 用作变量,因为它会被解析为加法,并会导致语法错误。你甚至不需要那个部分。您为 constance_val 正确执行了此操作,但无需保留 price_month_+i 的值,因为您只需要在每次循环迭代中使用它们。

这是一个固定的工作示例,稍作优化:

function change(){    
    var price_start = document.getElementById('price_start').value;
    for (var i = 1; i <= 14; i++) { 
        document.getElementById('price_month_'+i).value = price_start * i * 2;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="byBtn" value="Change" onclick="change()"/>
 
<input type="text" id="price_start" value="5">
<br>
<br>
<input type="text" id="price_month_1">
<br>
<br>
<input type="text" id="price_month_2">
<br>
<br>
<input type="text" id="price_month_3">
<br>
<br>
<input type="text" id="price_month_4">
<br>
<br>
<input type="text" id="price_month_5">
<br>
<br>
<input type="text" id="price_month_6">

【讨论】:

    【解决方案2】:

    您的代码中有语法错误...您应该将所有变量声明为var

    function change(){     
        var price_start = document.getElementById('price_start').value;
        for (var i = 1; i <= 14; i++) { 
            var constance_val = i*2;
            var price_month = price_start*constance_val;
            document.getElementById('price_month_'+i).value = price_month; 
        }
    }
    

    顺便说一句。由于您的按钮没有提交任何内容,您可能应该使用&lt;input type="button"&gt;(或&lt;button type="button"&gt;)而不是&lt;input type="submit"&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多