JavaScript - document.getElementByID with onClick(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript - 带有 onClick 的 document.getElementByID
基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
