检测鼠标单击图像并将其存储在数据库中

时间:2017-02-07 09:18:56

标签: jquery database mouseclick-event

我想检测鼠标在图像上的点击,并将所有点击点存储在数据库文件中。我尝试了但我只能检索最后一次点击而不是会话中的所有点击。 我的鼠标点击代码如下:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
    </script>
    <script>
      $(document).ready(function() 
      {
        $('img').click(function(f) 
        {
          var offset = $(this).offset();
          var X = (f.pageX-offset.left);
          var Y = (f.pageY-offset.top);
          var X1=[X];
          var Y1=[Y];
          $('#display').text('X: ' + X1 + ', Y: ' + Y1);
        });
      });
   </script>
  </head>
  <body>
    <img style="width:500px;"src="mouseclick.png"/>   
    <div id="display">
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

通过这样做,您可以保存每次ajax调用的所有点击。

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    var xPoint = e.pageX - offset.left;
    var yPoint = e.pageY - offset.top;
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
    $.ajax({
      url: "where you want to go example: /Admin/SavePoints",
      type:"POST",
      data:{xAxis:xPoint,yAxis:yPoint },
      success: function(data){
       alert("Saved");   
      }
      error: function(){
        alert("ERROR");
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px;">

更新小提琴:

$(document).ready(function() {
    var arrayOfXY = new Array();
    $('img').click(function(e) {
        var offset = $(this).offset();
        var xPoint = e.pageX - offset.left;
        var yPoint = e.pageY - offset.top;
        arrayOfXY.push({x:xPoint, y:yPoint});
    });
  
    $(".showCoordinates").on("click",function() {
        for (var i = 0; i < arrayOfXY.length; i++) {
            var x = arrayOfXY[i].x;
            var y = arrayOfXY[i].y;
            alert("x axis:"+x+" and y axis:"+y);
            console.log("x axis:"+x+" and y axis:"+y);
        }
    });
  
    $(".saveCoordinates").on("click",function() {
        $.ajax({
            url: "Ur url",
            type:"POST",
            data: {coordinates:arrayOfXY},
            success:function(data){
              alert("Success");
            },
            error: function(){
              alert("ERROR");
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px;">
<button class="showCoordinates">Show saved coordinates</button>
<button class="saveCoordinates">Save coordinates in DB</button>