2012-01-07 69 views
1

我想編寫一個函數,這樣我可以像這樣執行命令:編寫你自己的Jquery函數?

$("#Button").glow(); 

我有什麼重寫,或者我怎麼也得結構中的「發光」的功能,這樣我可以稱它爲我在上面做的方式?

+2

閱讀[文件](HTTP://文檔.jquery.com/Plugins/Authoring) – 2012-01-07 16:07:26

回答

9

看看plugin authoring。閱讀文檔。做和嘗試一些。例如像:

(function($) { 
    $.fn.glow = function(options) { 
     return this.each(function() {  
      // TODO: do something for each element that matched your selector 
     }); 
    }; 
})(jQuery); 
+4

-1的態度 – 2013-04-30 11:38:19

7
(function($) { 
    $.fn.glow = function() { 
     return this.each(function() { //<--optionally, parameters here 
      // your logic here 
      // `this` at this point refers to the DOM element 
     }); 
    } 
})(jQuery); //<-- Closure to allow using $ where $ is not jQuery any more 

return this.each(..)return能使鏈的jQuery插件,讓你可以使用:

$("selector").glow().anothermethod(); 
//If return was omitted, the previous line would throw an error 
1
jQuery.fn.glow = function() { 
    //Do Stuff 
} 
2
(function($){ 

    $.fn.glow = function() { 

    //your selected element is 'this' 
    this. ...//do your magic 

    }; 
})(jQuery); 

然後你就可以使用它像這樣:

$('#element').glow(); 

有關完整信息,請檢查第是:http://docs.jquery.com/Plugins/Authoring

9

您必須聲明一個jQuery之類的函數爲:

jQuery.fn.myPlugin = function() { 

    // Do your awesome plugin stuff here 

}; 

後這裏閱讀

$("#Button").myPlugin(); 

http://docs.jquery.com/Plugins/Authoring

相關問題