2015-01-15 94 views
0

我有一個事件偵聽器,即是這樣的(僞代碼):在鼠標懸停上添加事件,如何添加事件一次?

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

我預期的結果:當我懸停在畫布上繪製的具體路線,我可以點擊得到一個警報。

實際結果:當我在畫布上點擊我的線條時,出現很多提醒。我的猜測是:對於我移過元素的每個像素,都會添加點擊偵聽器。所以如果我將鼠標懸停在元素上,警報將會播放很多次。如果我將鼠標懸停在元素外部,則將移除每個移動到元素外部的像素的事件偵聽器。

有沒有更好的方法來做到這一點?

+0

看來你綁定了一個被多次調用的函數內部的click事件處理程序,所以事件處理程序一次又一次地被添加。 – adeneo 2015-01-15 15:27:25

+0

不知道我是否理解,但也許你想用jQuery的[one](http://api.jquery.com/one/)函數而不是'on'? – andrusieczko 2015-01-15 15:29:37

回答

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

謝謝,只是刪除事件,並重新添加它很好。 – ohyeah 2015-01-15 15:44:50

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>

0

jQuery有一個方法,可以讓你附加的事件,事件處理程序只有一次。 http://api.jquery.com/one/

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

從您的描述中,它聽起來像是更好地移除onmousemove並將所有代碼放在一個點擊中。

在onclick中添加如果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 
    } 
}) 

每當鼠標移動時,Onmouseover都會觸發1像素,因此它不適合綁定另一個函數。

如果您是否已存在你的元素

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

或像這樣的困境絕對必須這樣來做檢查......

與.off()可能工作的其他評論;我可能會誤解;但我認爲它會移除所有綁定,然後重新綁定您移動的每個像素的click(),這可能會導致後面出現很多性能問題,或許會出現這種情況?