开发者

Is there a way to simplify these 3 functions into 1 function? [closed]

开发者 https://www.devze.com 2023-04-04 11:24 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.
<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>


Of course . Pass your div id as an argument to the function . See http://jsfiddle.net/KsePr/ for a demo .

One word of caution - If you are trying to implement some kind of voting system on a webpage , you'll need to do the vote incrementing in at the server side , not the client side .


Try this:

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

Now you can call it with any element id you want, like:

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

Note that this will work with any number of elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消