在鼠标悬停时添加事件,如何仅添加一次事件?

时间:2015-01-15 15:24:31

标签: javascript jquery

我有一个事件监听器,就像这样(伪代码):

canvas.onmousemove = function (e) { checkCollision(e); };

var checkCollision = function(e){
    var context = canvas.getContext('2d');
    var coordinates = getMouseXY();

    // draw any shape with the context

    if(context.isPointInPath(coordinates.X, coordinates.Y){
          $(canvas).on('click', alertFunction, e);
          return; //stop the function from doing anything else
    }

    $(canvas).off('click', alertFunction, e);      
};

var alertFunction = function(e){
    alert("this alert should only show once per click");
};

我的预期结果:当我将鼠标悬停在画布上绘制的特定线上时,我可以点击以获取警报。

实际结果:当我在画布中单击我的行时,会收到很多警报。我的猜测:对于我在元素上移动的每个像素,都会添加点击侦听器。因此,如果我将鼠标悬停在元素上,警报将会播放很多次。如果我将鼠标悬停在元素外部,则会移动一个事件侦听器,以便移动到元素外部的每个像素。

有更好的方法吗?

4 个答案:

答案 0 :(得分:1)

您可以使用hover()功能:

$('div').hover(function() {
  alert('hoverd');
}, function() {
  alert('out of div');
});
div {
  padding: 30px;
  border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>hover</div>

答案 1 :(得分:1)

如果你这样改变怎么办?

canvas.onmousemove = function (e) { checkCollision(e); };

var checkCollision = function(e){
    var context = canvas.getContext('2d');
    var coordinates = getMouseXY();

    // draw any shape with the context

    if(context.isPointInPath(coordinates.X, coordinates.Y){
          $(canvas).off().on('click', alertFunction, e);
          return; //stop the function from doing anything else
    }
};

var alertFunction = function(e){
    alert("this alert should only show once per click");
};

答案 2 :(得分:0)

jQuery有一个方法,只允许您将事件附加到事件处理程序一次。 http://api.jquery.com/one/

$( "#foo" ).one( "mouseover", function() {
     checkCollision();
});

答案 3 :(得分:0)

根据您的描述,您最好删除onmousemove并将所有代码放入点击中。

在onclick中添加if isPointInPath函数和alertFucntion如果为true,否则不执行任何操作。

$(canvas).click(function() {
   var context = canvas.getContext('2d');
   var coordinates = getMouseXY();

   if(context.isPointInPath(coordinates.X, coordinates.Y){
      alertFunction(e);
      return; //stop the function from doing anything else
   }
})

每次鼠标在画布上移动1个像素时,Onmouseover会触发,因此它不适合绑定其他功能。

如果您绝对必须这样做,请检查您的元素是否已经绑定

$.data(!$(canvas).get(0), 'events' ).click) {
   $(canvas).on('click',alertfucntion, e}
}

或类似的东西......

.off()的另一条评论可能有用;我可能弄错了;但我认为它会删除你所有的绑定,然后重新绑定你移动的每个像素的click(),这可能会导致以后出现很多性能问题,或许?