最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

button - Javascript - How to program a click counter? - Stack Overflow

programmeradmin1浏览0评论

I have tried before, but it doesn't work. Is it any wrongs of the code?

<script type ="text/javascript">
function count()
{
var x = 0;
x += 1;
document.getElementById( "counting" ).value = x;
}
</script>
</head>
<body>

<input type ="button" value = "Click" onclick = "count()"/><br><br>
<input id = "counting" type = "text" />

</body>

I have tried before, but it doesn't work. Is it any wrongs of the code?

<script type ="text/javascript">
function count()
{
var x = 0;
x += 1;
document.getElementById( "counting" ).value = x;
}
</script>
</head>
<body>

<input type ="button" value = "Click" onclick = "count()"/><br><br>
<input id = "counting" type = "text" />

</body>
Share Improve this question asked Nov 23, 2009 at 12:05 Programme NewbieProgramme Newbie 1231 gold badge4 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

you need to move the line var x = 0; to somewhere outside of the function count in order for it to be in the global scope. This means that changes made to it by the function count will persist.

e.g.

var x = 0;
function count() {
    x += 1;
    document.getElementById( "counting" ).value = x;
}

X appears to be declared as a local variable, so it's going to be reset to zero every time the function is called. Try moving "var x = 0;" outside the function (into global scope).

You are initializing x to 0 every time the button is clicked. Try var x=0; outside the function.

发布评论

评论列表(0)

  1. 暂无评论