[英]Using setInterval() for a function with parameters in JavaScript
[英]Passing parameters using .call() inside a setInterval function
我正在嘗試做的是創建一個函數,只要按住鼠標按鈕就可以連續調用另一個函數。 我這樣做只是為了更好地理解.call()和回調。 這是我的代碼:
jQuery.fn.contmousedown = function(mousedownCallback){
var interval, self = this;
jQuery(this).mousedown(function(event){
interval = setInterval(function(self, event){
mousedownCallback.call(self, event);
console.log('on');
},0);
});
jQuery(this).mouseup(function(event){
clearInterval(interval);
});
}
$(document).contmousedown(function(e){
$('#run').html(e.pageX+', '+e.pageY);
});
我收到的錯誤是:
Uncaught TypeError: Cannot read property 'pageX' of undefined
當然,我每秒會收到300倍。 :)如果我將間隔聲明行更改為interval = setInterval(function(self){
然后我以大約300倍每秒的速度登錄到控制台,但我丟失了事件,所以我的問題是如何做到這一點我可以回調該函數並將事件參數傳遞給它嗎?
示例-http://jsfiddle.net/ZxKxD/
jQuery.fn.mousehold = function(mousedownCallback){ var interval, self = this, move_event; jQuery(this).mousemove(function(e){ move_event = e; }); jQuery(this).mousedown(function(click_event){ interval = setInterval(function(){ mousedownCallback.call(self, click_event, move_event); },0); }); jQuery(this).mouseup(function(){ clearInterval(interval); }); jQuery(this).mouseout(function(){ clearInterval(interval); }); } $(document).mousehold(function(click_event, move_event){ $('#run').html(click_event.pageX+':'+move_event.pageX+', ' +click_event.pageY+':'+move_event.pageY); });
setInterval
不會將參數傳遞給回調,因此請刪除self
和event
參數。 您這樣做不會“丟掉”事件。
$.fn.contmousedown = function(mousedownCallback)
{
var interval,
self = this;
$(this).mousedown(function(event)
{
interval = setInterval(function()
{
mousedownCallback.call(self, event);
console.log('on');
}, 0);
});
$(this).mouseup(function()
{
clearInterval(interval);
});
}
演示: http : //jsfiddle.net/mattball/9veUQ
那么如何獲得光標位置的連續更新?
使用mousemove
捕獲事件。
$.fn.contmousedown = function(mousedownCallback)
{
var interval,
self = this,
event;
$(this).mousemove(function(e)
{
event = e;
});
$(this).mousedown(function ()
{
interval = setInterval(function()
{
mousedownCallback.call(self, event);
}, 0);
});
$(this).mouseup(function()
{
clearInterval(interval);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.