如何计算随机图片的点击次数?

How to count clicks of random images?

我试图制作一个由鼠标点击触发的随机序列,并跟踪用户点击图像的次数。有人可以帮我吗?谢谢! 以下是我随机提取图像的代码:

<!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>