首页 > 解决方案 > 如何计算随机图片的点击次数?

问题描述

我正在尝试通过鼠标单击触发随机序列,并跟踪用户单击图像的次数。有人可以帮我吗?谢谢!以下是我随机拉取图像的代码:

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

标签: javascriptmouseclick-event

解决方案


假设您从 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>


推荐阅读