0

我希望能够显示按钮#1、按钮#2 的点击次数,并显示按钮#1+按钮#2 的点击总和。到目前为止,我所能展示的只是总和。

HTML

 <button id="1" onclick = "countCar('ferrari');">Button#1</button>
 <a>Ferraris</a><span id="ferrariCount"></span>

 <a id="showSum">SUM<span id="carCount"></span></a>

 <button id="2" onclick = "countCar('toyota');">Button#2</button>
 <a>Toyotas</a><span id="toyotaCount"></span>

Javascript

  var carCount = 0; 
  var ferrariCount = 0;
  var toyotaCount = 0;
  function countCar(type)

  {
    carCount = carCount + 1;
    document.getElementById('carCount').innerHTML = carCount;

    ferrariCount = ferrariCount + 1;
    toyotaCount = toyotaCount + 1;

     if(type =='ferrari'){document.getElementById('ferrariCount').innerHTML = ferrariCount;
             }else{
             document.getElementById('toyotaCount').innerHTML = toyotaCount;}
  };
4

3 回答 3

0

并改变

document.getElementById('toyotaCount')。interHTML = toyotaCount;}

于 2012-08-23T07:16:22.990 回答
0

如果(类型 = '1')

你为什么用这个?

它应该更改为

if(type === 'ferrari') 然后它将起作用。

还有它的innerHTML 一些错字

于 2012-08-23T07:17:19.083 回答
0

您的代码有点多余,因此我将其结构如下:

var counts = {
  'ferrari': 0,
  'toyota': 0,
  'total': 0
};

function countCar(type) {
  document.getElementById('carCount').innerHTML = ++counts['total'];
  document.getElementById(type + 'Count').innerHTML = ++counts[type];
}

而不是使用大量的全局变量,只需创建和对象将您的数字存储在其中。它使您的代码更清晰,更易于阅读。

于 2012-08-23T07:17:58.590 回答