2011-08-04 46 views
0

我創建了一個包含下面代碼的頁面。我需要警告一條消息。但它不起作用。爲什麼?鉤子在jQuery中切換

代碼:

$(document).ready(function() { 
    $.hook('toggle'); 
    $('#test').bind('onbeforetoggle', function(e){alert(e.type)}); 

    $('#btnHide').click(function() { 
     $('#divTest').toggle(); 

    }); 

}); 

jsFiddle demo

+0

爲什麼你認爲它應該工作? jQuery沒有'hook'方法。順便說一句。你沒有選擇jQuery作爲你的jsFiddle庫。 *編輯*:啊,你添加它作爲外部資源....從「選擇框架」列表中選擇它更容易。 –

+0

掛鉤必須是一個三方插件。你能給我們更多的信息,你的jsfiddle演示試圖使用mootools。 –

+0

我認爲他指的是這個:http://plugins.jquery.com/project/jqueryHook – nthpixel

回答

0

希望一些幫助

http://jsfiddle.net/TzCXC/

(function($){ 
    $.hook = function (fns) { 
     fns = typeof fns === 'string' ? 
      fns.split(' ') : 
      $.makeArray(fns) 
     ; 

     jQuery.each(fns, function (i, method) { 
      var old = $.fn[ method ]; 

      if (old && !old.__hookold) { 

       $.fn[ method ] = function() { 
        this.triggerHandler('onbefore'+method); 
        this.triggerHandler('on'+method); 
        var ret = old.apply(this, arguments); 
        this.triggerHandler('onafter'+method); 
        return ret; 
       }; 

       $.fn[ method ].__hookold = old; 

      } 
     }); 

    }; 

    $.unhook = function (fns) { 
     fns = typeof fns === 'string' ? 
      fns.split(' ') : 
      $.makeArray(fns) 
     ; 

     jQuery.each($.makeArray(fns), function (i, method) { 
      var cur = $.fn[ method ]; 

      if (cur && cur.__hookold) {    
       $.fn[ method ] = cur.__hookold;   
      } 
     }); 

    }; 
})(jQuery); 
+0

好吧,爲什麼我應該寫這麼多的代碼?請看http://plugins.jquery.com/project/jqueryHook – Rauf

+0

@mraufk - 其實,你的鏈接也使用3d方插件。請參閱[http://plugins.jquery.com/project/jqueryHook](http)中的鏈接[嘗試演示](http://github.com/aheckmann/jquery.hook/raw/master/test.html) ://plugins.jquery.com/project/jqueryHook),您可以在頁面源代碼''中找到腳本'