1.less typing
2.more flexible.
For example:
You can see the image below, use Map<> = new HashMap() can easily change HashMap to TreeMap
response.sendRedirect("other.view");
parameter,session,request.setAttribute req.getRequestDispatcher("hello.jsp").forward(req, resp);
RequestDispatcher dispatcher = req.getRequestDispatcher("other.view"); dispatcher.include(req, resp);
$.fn.greenify = function() { this.css( "color", "green" ); }; $( "a" ).greenify(); // Makes all the links green.
$.fn.greenify = function() { this.css( "color", "green" ); return this; } $( "a" ).greenify().addClass( "greenified" );
(function ( $ ) { $.fn.greenify = function() { this.css( "color", "green" ); return this; }; }( jQuery ));
(function( $ ) { $.fn.popup = function( action ) { if ( action === "open") { // Open popup code. } if ( action === "close" ) { // Close popup code. } }; }( jQuery ));
$.fn.myNewPlugin = function() {
return this.each(function() {
// Do something to each element here.
});
};
Notice that we return the results of .each() instead of returning this. Since .each() is already chainable, it returns this, which we then return. This is a better way to maintain chainability than what we've been doing so far.return this.each(function() { var link = $(this); link.css("color", setting.color) });6.讓一個plugin接受『一組設定』
(function ( $ ) { $.fn.greenify = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundColor: "white" }, options ); // Greenify the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));Example usage:
$( "div" ).greenify({ color: "orange" });
(function($) { $.fn.greenify = function(action, options) { var setting = $.extend({ color: "green", backgroundColor: "white" }, options); if (action === 'div') { return this.css({ color: setting.color, backgroundColor: setting.backgroundColor }); }; if (action === 'a') { return this.each(function() { var link = $(this); link.css("color", setting.color) }); } }; }(jQuery));template.html
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-1.12.0.min.js"></script> <script src="js/my_plugin.js"></script> <script> $(document).ready(function() { $("a").greenify("a", { color: "red" }); $("div").greenify("div", { color: "white", backgroundColor: "red" }); }); </script> <title>jQuery</title> <body> <a href="www.google.com.tw">GoogleGoog</a> <a href="www.yahoo.com.tw">YahooYahoo</a> <div> Hello </div> </body> </html>