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
基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
