2015-07-01 35 views
0

如何使用循环的JavaScript和使用var循环?如何在JavaScript上使用循环并在循环中使用var?

当点击按钮。这将是自动填充值输入类型文字与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+; 
    } 
} 
+0

可能重复http://stackoverflow.com/questions/5117127/use-dynamic- (或者你知道..使用一个数组或一个常规变量?看看你的控制台,你会意识到你不能命名变量'price_month_ + i +') – h2ooooooo

+0

也,你的'我'目前是隐含的全球 – LukeP

+2

http://jsfiddle.net/arunpjohny/wzd51poL/1/ –

回答

3

不能使用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">

0

你必须在你的代码的语法错误...你应该声明所有变量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; 
    } 
} 

btw。因为您的按钮不提交任何你应该使用<input type="button">(或<button type="button">),而不是<input type="submit">

[在JavaScript中使用动态变量名(指