【问题标题】:use a variable out of for loop在 for 循环外使用变量
【发布时间】:2016-05-30 13:57:51
【问题描述】:

我尝试运行此代码。但是当我将 x 设置为 loop 时,代码不起作用。

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;   
    }

【问题讨论】:

  • 你的错误信息是什么?
  • 你所说的“套出循环”是什么意思? jsfiddle.net/7msje7vr
  • 这段代码什么也没做
  • 您的for循环可能有问题,请尝试将for循环i &lt;= textbox.length的条件更改为i &lt; textbox.length

标签: javascript jquery for-loop scope


【解决方案1】:

看起来你的 for 循环的上限是 1 太大。试试:

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();

【讨论】:

    【解决方案2】:

    您的函数在价格输入的长度和这些价格输入中的潜在值上都失败了。

    在长度上使用&lt;= 将在不存在的价格输入“Uncaught TypeError: Cannot read property 'value' of undefined”时产生错误

    我不喜欢你的“count”这个名字,因为你没有计算任何东西,所以我更改了它以及一些变量以明确意图。

    此外,诸如“08”之类的值不会按预期(八进制)解析,“fred”也不会。

    考虑以下输入:

    <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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 2018-09-28
      • 2017-02-17
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2014-12-31
      相关资源
      最近更新 更多