简体   繁体   中英

Function in javascript only working once

I am using this function for a button:

points1 = 0;
function onclick1 (points1) {
    points1 += 5;
    document.getElementById("point1").innerHTML = points1;
}

Right now function only works on the first button click but not on subsequent clicks. How do I fix it?

You are passing points1 in as a var in the function. Try and change it to -->

points1=0;

function onclick1(){
points1+=5;
document.getElementById("point1").innerHTML=points1;

}

You've declared points1 as a function parameter, so it hides the global variable of the same name. Remove that parameter and it should work:

var points1=0;
function onclick1(){
    points1+=5;
    document.getElementById("point1").innerHTML=points1;
}

Try this

<!DOCTYPE html>
<html>
<head>
<script>
point1 = 0;
function myFunction()
{
point1 += 5;
document.getElementById("demo").innerHTML=point1;
}
</script>
</head>
<body>

<p>Click the button to trigger a function.</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM