0
    function showNumber(selectId, divNumber) {
    //this takes value from select option and grabs div for displaying it
    var select = document.getElementById(selectId);
    var noItems = document.getElementById(divNumber);

//loop for creating 0-20 drop down
    for (var i = 0; i <= 20; i++) {
    var option = document.createElement('option');
    option.innerHTML = i;
    option.value = i;

    select.appendChild(option);
    }

    //onchange shows in a div how many items were selected
    select.onchange = function () {
    var noZero = select.value;
    if (noZero > 0) {
    noItems.innerHTML = noZero;
    } else noItems.innerHTML = " ";
    };
    }

    //function takes parameters of the previous one and displays number of items of a particular product in a div
    function showDivs(){
    showNumber('item1', 'div1');
    showNumber('item2', 'div2');
    showNumber('item3', 'div3');
    showNumber('item4', 'div4');
    }

我的问题是我想添加所有产品(item1、item2 等)的数量以计算它们的总数。我似乎没有得到任何帮助,非常感谢任何帮助!...

4

1 回答 1

0

在使用您的函数初始化项目时构建一个选择框数组showNumber(),然后在您的onchange事件中运行一个总计函数来检查每个选择框中的值。

演示 jsfiddle

// totaling vars (add #1)
var totalDiv = document.getElementById("divTotal"),
    items = [];

function showNumber(selectId, divNumber) {
  var select = document.getElementById(selectId);

  select.onchange = function () {
    ...
    calcTotal(); // run the total calculation with this event (add #4)
    ...
  };

  // add item to array (for checking totals) (add #2)
  items.push(select);
}

...    

// calculate totals using the items array (add #3)
function calcTotal() {
  var totalQty = 0,
      itemLen = items.length;

  // loop through the items, sum values
  for (var i = 0; i < itemLen; i++) {
    totalQty += parseInt(items[i].value);
  }

  // show total
  totalDiv.innerHTML = totalQty;
}
于 2013-01-13T17:04:33.953 回答