简体   繁体   English

JavaScript - 带有 onClick 的 document.getElementByID

[英]JavaScript - document.getElementByID with onClick

I'm trying to code a simple game in an HTML document just for fun.我正在尝试在 HTML 文档中编写一个简单的游戏,只是为了好玩。 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语句,它应该更改图像及其onClick值...

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.图像将成功更改,但实际的 onClick 保持不变。 Checking the console, it throws no errors, either.检查控制台,它也不会引发任何错误。

The onclick property is all lower-case, and accepts a function , not a string. onclick属性都是小写的,并且接受一个函数,而不是一个字符串。

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

See also addEventListener .另请参阅addEventListener

In JavaScript functions are objects.在 JavaScript 中, 函数是对象。

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"也许您可能想使用“addEventListener”

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

Hope it's still useful for you希望它仍然对你有用

Sometimes JavaScript is not activated.有时 JavaScript 未激活。 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 '如果您在无法访问的页面内使用代码,请删除 和 标记并尝试在图像标记内的图片中使用 'onload=()'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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