javascript - 如何计算随机图片的点击次数?
问题描述
我正在尝试通过鼠标单击触发随机序列,并跟踪用户单击图像的次数。有人可以帮我吗?谢谢!以下是我随机拉取图像的代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
function changePic()
{
var num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
document.getElementById("p").value++;
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="changePic()" /></p>
</div>
</body>
解决方案
假设您从 1 开始您的图像序列,您可以使用计数器来计算您的图像点击次数。
单击图像元素时,buttonclick 函数将跟踪用户单击图像的次数。然后更改您当前的图像序列号,这将显示不同的图像。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
const counter = {};
let num = 1;
function changePic()
{
num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
counter[num] = (counter[num] || 0) + 1;
console.log(counter)
//if you want to show current count for the sequence, you can use console.log(counter[num])
changePic()
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="buttonclick()" /></p>
</div>
</body>
推荐阅读
- java - “mailR”包的问题 - 在 RJavaClassLoader.findClass 处给出 java.lang.ClassNotFoundExceptio
- javascript - 如何在 Postman 中“以编程方式”设置集合变量的初始值?
- r - panelAR:相同的回归与更多的观察导致记忆错误
- javascript - 检查数组数组是否包含javascript中的值
- django - Django 中的模型字段
- android - 错误:找不到吸气剂:“小部件”。小部件.icon
- spring - 具有原生查询的基于类的投影
- javascript - Next.js - 预期的服务器 HTML 包含匹配在
- c++ - GLFW窗口不呈现关闭按钮?
- python - 如何在 Telethon 中将相册作为新消息发送