概述
// 立刻执行函数 (function($){ // code })(jQuery);
参数说明
形参: $
实参: jQuery
闭包的作用
-
避免全局依赖
-
避免第三方破坏
-
兼容jQuery操作符'$'和jQuery;
/*comment.js*/ ;(function($){ //消息显示 $.message=function(content){ $('#message').attr('data-content',content); $('#message').popover('show'); setTimeout(function() { $('#message').popover('hide'); },2000) } //隐藏标签 $.hidden = function(id){ var id = '#'+id; if(!$(id).hasClass('hidden')){ $(id).addClass('hidden'); } } //显示标签 $.display= function(id){ var id = '#'+id; if($(id).hasClass('hidden')){ $(id).removeClass('hidden'); } } function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } //POST请求 $.postJSON = function(url, args, callback) { //args._xsrf = getCookie("_xsrf"); args.csrfmiddlewaretoken = getCookie("csrftoken"); $.ajax({url: url, data: args, dataType: "json", type: "POST", success: function(response) { callback(response); }}); }; })(jQuery);
使用
index.html
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="./comment.js"></script> </head> <body> test </body> </html>