我正在尝试通过鼠标单击触发随机序列,并跟踪用户单击图像的次数。有人可以帮我吗?谢谢!以下是我的随机提取图像的代码:
<!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>
尝试使clickCounter
对象的键等于图片编号,最好在JS中使用onclick
方法,但在html中不使用]]
let num = 1; const clickCounter = {}; const randomPic = document.getElementById('randomPic') randomPic.onclick = function(){ clickCounter[num] = (clickCounter[num] || 0) + 1; changePic(); console.log(clickCounter); // if you need } function changePic() { num = Math.ceil(Math.random()*9); randomPic.src = num + ".jpg"; }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>The Door Moment</title> </head> <body> <p align="center"><img src = "1.jpg" id = "randomPic" width="400px" height="600px"/></p> </body> </html>