有没有办法将这3个函数简化为1个函数?

时间:2011-09-12 11:21:53

标签: javascript html simplify

<html>
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Vote!</title>
    <script type="text/javascript">
    var x1 = 0;
    function countClicks() {
        x1 += 1
        document.getElementById( "counting" ).innerHTML = x1;
       ClickCount++;
       return true;
    }
    </script>

    <script type="text/javascript">
    var x2 = 0;
    function countClicks1() {
        x2 += 1
        document.getElementById( "counting1" ).innerHTML = x2;
        ClickCount++;
        return true;
    } 
    </script>

    <script type="text/javascript">
    var x3 = 0;
    function countClicks2() {
        x3 += 1
        document.getElementById( "counting2" ).innerHTML = x3;
        ClickCount++;
        return true;
    }
    </script>
</head>
<body>
 <div id="chart1">
 <ul>
  <li>
   <img src="../Pictures/BWS + L.A +KUSH/Game.RED_Album_Cover.jpg" alt="red album"><br/>
   <input type="button" value="VOTE" name="clickOnce" onclick="return countClicks();" />
   <div id="counting"></div>
  </li>
  <li>
   <img src="../Pictures/BWS + L.A +KUSH/Game.RED_Album_Cover.jpg" alt="red album"><br/>
   <input type="button" value="VOTE" name="clickOnce" onclick="return countClicks1();" />
   <div id="counting1"></div>
  </li>
  <li>
   <img src="../Pictures/BWS + L.A +KUSH/Game.RED_Album_Cover.jpg" alt="red album"><br>
   <input type="button" value="VOTE" name="clickOnce" onclick="return countClicks2();" />
   <div id="counting2"></div>
  </li>
 </ul>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

当然。将您的div id作为参数传递给函数。有关演示,请参阅http://jsfiddle.net/KsePr/

提醒一句 - 如果您尝试在网页上实施某种投票系统,则需要在服务器端而不是客户端进行投票递增。

答案 1 :(得分:1)

试试这个:

var countMap = {};
function countClicks(id) {
    countMap[id] = countMap[id] + 1 || 1;
    document.getElementById(id).innerHTML = countMap[id];
}

现在您可以使用您想要的任何元素ID来调用它,例如:

countClicks('counting');
countClicks('counting1');
countClicks('counting2');

请注意,这适用于任意数量的元素。