Javascript 使用for循环外的变量

Javascript 使用for循环外的变量,javascript,jquery,for-loop,scope,Javascript,Jquery,For Loop,Scope,我试着运行这个代码。但是当我将x设置为循环外时,代码不起作用 function count(){ var textbox,x=0; textbox = document.getElementsByClassName('price'); for (var i=0;i<=textbox.length;i++) { x += parseInt(textbox[i].value); }

我试着运行这个代码。但是当我将x设置为循环外时,代码不起作用

function count(){
        var textbox,x=0;
        textbox = document.getElementsByClassName('price');
        for (var i=0;i<=textbox.length;i++) {
            x += parseInt(textbox[i].value);
        }       
        document.getElementById('total').value=x;   
    }
函数计数(){
变量文本框,x=0;
textbox=document.getElementsByClassName('price');

for(var i=0;i看起来for循环的上限太大了。请尝试:

function count(){
        var textboxes,x=0;
        textboxes = document.getElementsByClassName('price');
        for (var i=0;i<textboxes.length;i++) {
            x += parseInt(textboxes[i].value);
        }       
        document.getElementById('total').value=x;   
    }

count();
函数计数(){
变量文本框,x=0;
textboxs=document.getElementsByClassName('price');

对于(var i=0;i,您的函数在价格输入的长度和这些价格输入中的潜在值上都失败


使用
你的错误消息是什么?你说的“设置循环”是什么意思?此代码不起作用。你可能对for循环有问题,请尝试更改for循环的条件
i
<input class="price" value="33" />
<input class="price" value="3" />
<input class="price" value="-23" />
<input class="price" value="13" />
<input class="price" value="08" />
<input class="price" />
<input class="price" value="fred" />
<input id="total" />
function totalPrice() {
  var total = 0;
  var prices = document.getElementsByClassName('price');
  var len = prices.length;
  for (var i = 0; i < len; i++) {
    total += isNaN(parseInt(prices[i].value, 10)) ? 0 : parseInt(prices[i].value, 10);
  }
  document.getElementById('total').value = total;
}
totalPrice();