简体   繁体   中英

JavaScript - document.getElementByID with onClick

I'm trying to code a simple game in an HTML document just for fun. In it, there is an image which adds to your score when clicked.

I created a simple if statement within the score-adding function which should change the image and what its onClick value is...

if (foo == 1) {
    document.getElementById("test").src = "images/test2.png";
    document.getElementById("test").onClick = "foo2()";
}

...but it doesn't work. The image will be successfully changed, but the actual onClick remains the same. Checking the console, it throws no errors, either.

The onclick property is all lower-case, and accepts a function , not a string.

document.getElementById("test").onclick = foo2;

See also addEventListener .

In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){
    prompt('Hello world');
}
window.onload = prepareButton;

function prepareButton()
{ 
   document.getElementById('foo').onclick = function()
   {
       alert('you clicked me');
   }
}

<input id="foo" value="Click Me!" type="button" />

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

Sometimes JavaScript is not activated. Try something like:

<!DOCTYPE html>
<html>
  <head>

    <script type="text/javascript"> <!--
      function jActivator() {
        document.getElementById("demo").onclick = function() {myFunction()};
        document.getElementById("demo1").addEventListener("click", myFunction);
        }
      function myFunction( s ) {
        document.getElementById("myresult").innerHTML = s;
        }
    // --> </script>
    <noscript>JavaScript deactivated.</noscript>
    <style type="text/css">
    </style>
  </head>
  <body onload="jActivator()">
    <ul>
      <li id="demo">Click me -&gt; onclick.</li>
      <li id="demo1">Click me -&gt; click event.</li>
      <li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
    </ul>
    <div id="myresult">&nbsp;</div>
  </body>
</html>

If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '

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