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


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01