如何多次添加变量?

时间:2013-11-30 21:57:55

标签: javascript operators

我一直试图让它点击一个按钮,它增加了金额 - 完成了!那你怎么这么做多次?在,如何每次添加1?这是我到目前为止的一些JavaScript:

function stickAmount() {
    var y = 1;
    var stickNo = document.getElementById("stickNumber");
    stickNo.innerHTML = "Sticks: " + y;
}

和HTML:

<div id="stickNumber" style="margin-left:10px; margin-top:10px;"></div>

3 个答案:

答案 0 :(得分:1)

var y=1  // move the variable outside of the function
function stickAmount()
{

var stickNo=document.getElementById("stickNumber")
stickNo.innerHTML="Sticks: "+y;
y++ // increment y by 1 every time the function is called
}

DEMO

答案 1 :(得分:0)

我已经设置了一个快速的jsfiddle来演示它是如何完成的。

http://jsfiddle.net/benwong/mDTFL/

HTML

Sticks: <span id="NumberOfSticks"></span>

<button id="AddStickButton">Add</button>

的Javascript

var numberOfSticks = 1;

var numberOfSticksSpan = document.getElementById("NumberOfSticks");
numberOfSticksSpan.innerHTML = numberOfSticks;

function addStick() {
    numberOfSticks++;
    numberOfSticksSpan.innerHTML = numberOfSticks;
}

var addStickButton = document.getElementById("AddStickButton");
addStickButton.addEventListener("click", addStick, false);

最重要的是为函数外部的棒数定义变量,增加棒数。

我将“Sticks:”移动到HTML中,因为您只需要更改数字。

答案 2 :(得分:-1)

function stickAmount()
{
var y=1;
var stickNo=parseInt(document.getElementById("stickNumber"));
stickNo.innerHTML="Sticks: "+y;
}


setInterval("stickAmount()",500)