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 API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01