2012-01-13 70 views
2

我创建了一个名为“onEnter”的jQuery函数。 它在运行时效果很好,但我需要在任何时候触发事件。 Somethink like this:jQuery:在自定义事件上触发函数

$(obj).onEnter(function(){ doSomething(); }); 

这就像一个魅力。 后来我想触发:

$(obj).onEnter(); 

但这似乎并不工作。 这是我的代码。 在此先感谢。

$.fn.extend({ 
    onEnter: function(fn) { 
     this.each(function() { 
      new $.onEnter(this, fn); 
     }); 
     return this; 
    } 
}); 

$.onEnter = function(obj, fn) { 
    if(typeof fn == 'function') 
    { 
     $(obj).keypress(function(e){ 
      if(e.which == 13) 
      { 
       e.preventDefault(); 
       fn(obj); 
      } 
     }); 
    }; 
    return; 
}; 
+0

为什么你使用'new':

所以你可以做这样的事情? – 2012-01-13 00:27:38

回答

0

我认为您正在寻找jQuery .trigger()

$('#foo').bind('custom', function(event, param1, param2) 
{ 
    alert(param1 + "\n" + param2); 
}); 

$('#foo').trigger('custom', ['Custom', 'Event']); 
相关问题