在setInterval函数内部使用.call()传递参数
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);
});
};
演示:http://jsfiddle.net/mattball/dVaWS/
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- Function.prototype.call和Function.protoype.all只应用一个参数
- 为什么要将Array.prototype.slice.call与参数一起使用
- 在setInterval函数内部使用.call()传递参数
- 在这种情况下,有什么方法可以向`.call()`发送更多的参数吗
- 处理 Array.prototype.slice.call(参数)的更简洁方法
- Javascript call()函数-额外的参数
- .call()函数将函数作为参数而不是结果传递
- Meteor.call'加载'参数
- .call() / .apply()不带参数VS简单地用()圆括号调用函数
- 使用javascript .call()传递参数给匿名函数
- Array.prototype.slice.call(arguments)和Array的区别.应用(null,参数)
- .call方法参数'['和']'习俗
- 使用 .call() 时传递参数
- 当使用call()时,如何停止Ember渲染抱怨已弃用的无引号参数
- 将function.prototype.call生成的函数作为参数传递时,Array.prototype.map不是函数
- AJAX XHR-Call创建无效参数异常