简体   繁体   中英

Why does my clickable image not work?

I am trying to make a version of cookie clicker to practice making games but the important part doesn't work: When you click the cookie, nothing happens?

<!DOCTYPE html>
<html>
<head>
    <link rel='stylesheet' href='style.css'/>
    <script language="javascript">

    </script>
</head>
<body>
    <div id="cookie" style="cursor:pointer"><img src="http://img1.wikia.nocookie.net/__cb20130827014912/cookieclicker/images/thumb/5/5a/PerfectCookie.png/250px-PerfectCookie.png"></div>
    <div>
    <script language="javascript">
        //variables:
        var cookieClicks = 0;
        var cookieClicked;
        //code:
        var cookie = document.getElementById("cookie").onclick = cookieClicked(){
            return true;
        };         // gets the element

        //checks if cookie is clicked + add cookie
        if(cookieClicked === true){
            cookieClicks ++;
        }
        document.write(cookieClicks + " Cookies");
    </script>
    </div>
</body>
</html>

What you're currently doing is not the correct way to handle div click event. Assuming you want to increment cookieClicks and display the value of cookieClicks followed by " Cookies" each time the div is clicked, change your script to below

<script language="javascript">

    //variables:
    var cookieClicks = 0;

    function cookieClicked() {
        cookieClicks++;
        alert(cookieClicks + " Cookies");
    }
</script>

and add onclick="cookieClicked();" to the cookie div

<div id="cookie" style="cursor:pointer" onclick="cookieClicked();"><img     src="http://img1.wikia.nocookie.net/__cb20130827014912/cookieclicker/images/thumb/5/5a/PerfectCookie.png/250px-PerfectCookie.png"></div>

Working demo: http://jsfiddle.net/p87zks60/

The code inside onclick event handler ( cookieClicked ) executes whenever user click on the image. So you should do the job in the event handler, moreover you should use function before the name of event handler, this name is optional if you use function

var cookieClicks = 0;    
var cookie = document.getElementById("cookie").onclick = function cookieClicked()
{
       cookieClicks ++;
 };         // gets the element

may be try this:

 var cookieClicks = 0; function cookieClicked() { document.getElementById("count").innerHTML= ++cookieClicks + " Cookies"; } 
  <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='style.css'/> <script language="javascript"> </script> </head> <body> <div id="cookie" style="cursor:pointer" onclick="cookieClicked()"><img src="http://img1.wikia.nocookie.net/__cb20130827014912/cookieclicker/images/thumb/5/5a/PerfectCookie.png/250px-PerfectCookie.png"></div> <div> <p id="count"></p> </div> </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