JavaScript - 带有 onClick 的 document.getElementByID [英] JavaScript - document.getElementByID with onClick

查看:26
本文介绍了JavaScript - 带有 onClick 的 document.getElementByID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 HTML 文档中编写一个简单的游戏只是为了好玩.其中有一张图片,点击后会增加您的分数.

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.

我在得分添加函数中创建了一个简单的 if 语句,它应该更改图像以及它的 onClick 值是什么...

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()";
}

...但它不起作用.图像将成功更改,但实际的 onClick 保持不变.检查控制台,它也没有抛出任何错误.

...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.

推荐答案

onclick 属性都是小写的,并且接受一个函数,而不是一个字符串.

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

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

另请参阅 addEventListener.

See also addEventListener.

这篇关于JavaScript - 带有 onClick 的 document.getElementByID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆