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

问题描述 投票:0回答:2

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

<!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>
javascript mouseclick-event
2个回答
0
投票

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

0
投票

尝试使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>
© www.soinside.com 2019 - 2024. All rights reserved.