开发者

Store a integer javascript

Hi for instance if i have a integer that starts at 20 and then when i click button one it adds 10 to that 20 and then button 2 开发者_开发问答adds 4 ontop of the current count how would i do this ?


have a global variable start with a value of 20, and then attach a function to the button click event for the two buttons, one of them adds 10 to the variable, the other adds 4 to the variable. You might want to consider trying a problem and having some semi working code to show that you actually made an effort, otherwise chances are you are just going to get downvoted.


This might be what you are looking for:

<script type="text/javascript">
    var currentCount = 20;
</script>
<button id="button1" onclick="currentCount+=10;">Increase with 10</button>
<button id="button2" onclick="currentCount+=4;">Increase with 4</button>
<button id="show_currentCount" onclick="alert(currentCount);">Show count</button>


Something like this should work. Notice that it follows best practices and doesn't leak any variables into the global scope.

<button id="one" value="10">Add Ten</button>
<button id="two" value="4">Add Four</button>

<script>

    (function() {
        var myNumber = 20;

        var addValue = function() {
            myNumber+= +this.value;
        };

        var bindAdders = function() {
            var arr = [].splice.call(arguments);
            for (var i = 0, len = arr.length; i < len; i++) {
                document.getElementById(arr[i]).onclick = addValue;
            }
        };

        bindAdders('one', 'two');
    })();

</script>


<body onload="updateCounter()">
  <span id="counter">x</span>
  <button onclick="javascript:x+=10;updateCounter();return false;">+10</button>
  <button onclick="javascript:x+=4;updateCounter();return false;">+4</button>

  <script>
    window.x = 20;
    window.updateCounter = function() {
      document.getElementById("counter").innerHTML = String(x);
    };
  </script>
</body>

See jsfiddle.


This might help.

<html>
<script>
    var someValue=0;

    function addValue(parm){
        someValue += parm;
        currentValueLabel.innerText = someValue;
    }
</script>
<body onload="addValue(20);">
    <input type="button" value="Add 2" onclick="addValue(2);" />
    <input type="button" value="Add 4" onclick="addValue(4);"/>
    <span id="currentValueLabel"></span>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜