如何使用按钮按下事件增加JavaScript变量

时间:2009-05-08 00:07:26

标签: javascript

我可以创建一个javascript变量并在按下按钮时递增该变量(不提交表单)。 谢谢!

9 个答案:

答案 0 :(得分:41)

是:

<script type="text/javascript">
var counter = 0;
</script>

<button onclick="counter++">Increment</button>

答案 1 :(得分:10)

这样做的纯粹方法是向按钮添加事件处理程序,而不是将行为与内容混合(LSM,分层语义标记)

<input type="button" value="Increment" id="increment"/>

<script type="text/javascript">
    var count = 0;
    // JQuery way
    $('#increment').click(function (e) {
        e.preventDefault();
        count++;
    });
    // YUI way
    YAHOO.util.Event.on('increment', 'click', function (e) {
        YAHOO.util.Event.preventDefault(e);
        count++;
    });
    // Simple way
    document.getElementById('increment').onclick = function (e) {
        count++;
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    };
</script>

答案 2 :(得分:6)

<script type="text/javascript">
var i=0;

function increase()
{
    i++;
    return false;
}</script><input type="button" onclick="increase();">

答案 3 :(得分:4)

我需要查看此脚本的结果,并且能够通过合并以下内容来实现:

var i=0;

function increase()
{
i++;
document.getElementById('boldstuff').innerHTML= +i;
}

<p>var = <b id="boldstuff">0</b></p>
<input type="button" onclick="increase();">

首先添加“script”标记,并在函数结束花括号下面添加一个结束脚本标记。当我尝试它时,返回false导致firefox挂起。根据我的经验,所有其他解决方案都没有显示增量的结果。

答案 4 :(得分:1)

使用type = "button"代替"submit",然后为其添加onClick处理程序。

例如:

<input type="button" value="Increment" onClick="myVar++;" />

答案 5 :(得分:0)

<head>
<script type='javascript'>
var x = 0;
</script>
</head>
<body>
  <input type='button' onclick='x++;'/>
</body>

[Psuedo code,上帝,我希望这是对的。]

答案 6 :(得分:0)

是的,假设您的变量位于全局命名空间中:

<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>

答案 7 :(得分:0)

我相信你需要类似以下内容:

<script type="text/javascript">
var count;
function increment(){
    count++;
}
</script>

...

<input type="button" onClick="increment()" value="Increment"/>

<input type="button" onClick="count++" value="Increment"/>

答案 8 :(得分:0)

有类似的问题。需要将尽可能多的文本输入附加到表单。使用jQuery的功能是问题的答案:

<div id='inputdiv'>
<button id='mybutton'>add an input</button>
</div>

<script>
var thecounter=0; //declare and initialize the counter outside of the function
$('#mybutton').on('click', function(){
thecounter++;
$('#inputdiv').append('<input id="input'+thecounter+'" type="text/>);
});
</script>

将计数添加到每个新输入id会产生唯一ID,这使您可以使用jQuery serialize()函数获取所有值。