简体   繁体   中英

Javascript code for a increment counter based on number of clicks not working?

I was working on Udacity Javascript design course I need to increase the counter when image is clicked each time. But eventually I can't figure out what is wrong here that is not letting the code work. The link in Jfiddle is http://jsfiddle.net/mAKOV/uoyzrLn6/4/

 function clickdone() { var catpic = document.getElementById("catpic"); var counter = document.getElementById("counter"); var count = counter.innerHTML; count++; counter.innerHTML = count; } 
 <img id="catpic" src="http://apurrfectcat.files.wordpress.com/2011/08/2-cats.jpg" style="height:400px; width:600px;" onclick="clickdone();" /> <br> <div> <p>Cat Count</p> <span style="text:bold;">:</span> <span id="counter">0</span> </div> 

Your jsFiddle does not work because you have to set the onload setting in the upper left to No Wrap in <head> . This allows your clickdone() function definition to be in the global scope where the click handler can find it. As you had it, your function was defined inside an onload handler function which means it is in a private scope and the click handler cannot access it.

And, you also had a typo, missing the "f" in "function".

Changing that makes it work fine here: http://jsfiddle.net/jfriend00/uoyzrLn6/3/

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