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

Adding events on mouseover, how do you add an event only once?

本文关键字:添加 事件 一次 悬停 鼠标      更新时间:2023-09-26

我有一个事件侦听器,它的工作原理是这样的(伪代码):

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");
};

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

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

有没有更好的方法可以做到这一点?

如果你这样改变呢?

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");
};
您可以使用

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>

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

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

从您的描述来看,您最好删除 onmousemove 并将所有代码放在单击中。

在 onclick 中添加 if isPointInPath 函数,如果为 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(),这可能会导致以后出现很多性能问题,也许?