utils.js:可供其他页面共享的js
1.将点击事件抽象到utils.js中
·这种方法写完之后能够保证js的优美,当页面有多个click事件时能够避免代码重复,并且将click事件集中到一起
utils.js
/**
* Created by 111 on 2016/3/10.
*/
var utils = {};
utils.quick ={
click:function(method,node){
var list = null;
if(node){
list = $(node).find("[data-click]");
}else{
list = $("[data-click]");
}
list.on("click",function(eventObject){
//this指当前对象,若为save,则this指<button id="goHome" data-click="save">data测试save</button>
var click =$(this).data("click");
if(click && method[click]){ //获取button的附加click元素
return method[click].apply(this,[eventObject]);
}
});
},
offClick:function(node){
if(node){
$(node).find("[data-click]").off('click');
}else{
$("[data-click]").off('click');
}
}
};
·使用data-click属性来自定义点击方法名
页面
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link rel="stylesheet" href="${resource}/css/index.css?revision=${revision}">
<title></title>
<script type="text/javascript" src="${resource}/lib/jquery/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="${resource}/js/utils.js"></script>
<script type="text/javascript">
$(document).ready(function(){
utils.quick.click({
save:function(){
utils.quick.offClick("#save");//取消绑定点击事件,第二次点击不会相应
alert("save");
}
},"#save")//只有id为save的标签内的含有data-click属性的标签会被查找出来,绑定点击事件,
//如果省略则所有的具有data-click属性的元素都会查找出来然后判断
})
</script>
</head>
<body>
<div id="save">
<button id="goHome" data-click="save">data测试save</button>
</div>
<button id="go" data-click="query">data测试query</button>
</body>
</html>
多个data-click 属性可以这样写:
$(document).ready(function(){
utils.quick.click({
save:function(){
alert("save");
},
query:function(){
alert("query");
}
});
});
2.生成全局唯一标识符(UUID):通常可作为一个id使用,基本不会重复
utils.uuid= {
uuid:function(){
var d = new Date().getTime();
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){
var r = (d+Math.random()*16)%16 |0; // Math.random()*16 随机产生0-16之间的小数 % 模运算即取余
d = Math.floor(d/16); //round()四舍五入;floor()向上取整;ceil()向下取整;
return (c = 'x'?r:(r &0x7 |0x8)).toString(16);
});
return uuid;
}
};
js调用
alert(utils.uuid.uuid());
3.js模板引擎nano的使用:就不需要再去拼html了
utils.template = {
// JS模板工具 https://github.com/trix/nano
/**
* @param template 静态的模板,模型使用{object.name}的形式
* @param data 填充的数据对象
* @returns {XML|string|void}
*/
nano: function (template, data) {
return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
var keys = key.split("."), v = data[keys.shift()];
for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
return (typeof v !== "undefined" && v !== null) ? v : "";
});
}
};
·语法:
utils.template.nano(template,data);//template指填充数据的模板,可以为静态模板,写在页面上,data指用来填充的数据
简单使用
<!--jsp1.2默认不使用el表达式,如果遇到el表达式没解析,可以试试加上这个-->
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<link rel="stylesheet" href="${resource}/css/index.css?revision=${revision}">
<title></title>
<script type="text/javascript" src="${resource}/lib/jquery/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="${resource}/js/utils.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data = { //模拟填充的数据
user: {
login: "tomek",
first_name: "Thomas",
last_name: "Mazur",
account: {
status: "active",
expires_at: "2009-12-31"
}
}
}
var item = utils.template.nano($("#templateTest").html(),data);
$("#nano-test").html(item);
// $("#nano-test").html(utils.template.nano("<p>Hello {user.first_name} {user.last_name}! Your account is <strong>{user.account.status}</strong></p>", data));
})
</script>
</head>
<body>
<div id="nano-test"></div>
//静态模板,或者不使用直接用js中注释的方法插入
<script type="text/html" id="templateTest">
<p>Hello {user.first_name} {user.last_name}! Your account is <strong>{user.account.status}</strong></p>
</script>
</body>
</html>
异步请求list数据,不分页
<%--
Created by IntelliJ IDEA.
User: 111
Date: 2016/2/10
Time: 11:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCtype html>
<html>
<head>
<%--<script type="text/javascript" src="../public/js/amd_test.js"></script>--%>
<script type="text/javascript" src="../public/js/utils.js"></script>
<script type="text/javascript" src="../public/lib/jquery/jquery-2.1.3.min.js"></script>
<title></title>
<script type="text/javascript">
window.onload = function(){
$.ajax({ //请求到list数据,list保存的对象含有name和sex字段
url:'../test/data',
dataType:'json',
method:'post',
async:false,
success:function(data){
$.each(data,function(index,item){
$("#tbody").append(utils.template.nano($("#template-list").html(),item));
})
},
error:function(XMLHttpRequest ,textStatus,errorThrown){
console.log(XMLHttpRequest.status+"/n"+XMLHttpRequest.statusText+"/n"+errorThrown+"/n");
}
})
}
</script>
</head>
<body>
<div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>性别</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
<script type="text/html" id="template-list">
<tr>
<td>{name}</td>
<td>{sex}</td>
</tr>
</script>
</body>
</html>
分页的后期根据前端分页插件提供
4.美化页面的弹出框和确定框(需要bootstrap插件 ,需要上面的nano js引擎,uuid)
·alert/confirm utils.js
utils.modal = {
/**
* myAlert
* @param title 标题 不填则默认
* @param body 内容
* @param callback 回调函数
*/
myAlert: function () {
var settings = resolveModal.apply({}, arguments);
myAlert.open(settings);
},
/**
* myConfirm
* @param title 标题
* @param body 内容
* @param callback 回调函数
*/
myConfirm: function () {
var settings = resolveModal.apply({}, arguments);
myConfirm.open(settings);
}
};
var resolveModal = function () {//解析调用时的参数,并返回
var settings = null;
if (arguments.length == 1) {//仅一个参数
if ($.type(arguments[0]) == 'string') {
settings = {
body: arguments[0]
}
} else if ($.type(arguments[0]) == 'object') {
settings = arguments[0];
} else if ($.type(arguments[0]) == 'function') {
settings = {
callback: arguments[0]
}
}
} else if (arguments.length == 2) {//两个参数
if ($.type(arguments[1]) == 'function') {
settings = {
body: arguments[0],
callback: arguments[1]
}
} else {
settings = {
title: arguments[0],
body: arguments[1]
}
}
} else if (arguments.length == 3) {//三个参数
settings = {
title: arguments[0],
body: arguments[1],
callback: arguments[2]
}
}
return settings;
};
var myAlert = {
id: null,
template: '<div class="modal fade" id="{id}" style="width: 360px" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
settings: {
title: '消息提示',
body: '消息提示'
},
init: function () {
$('#' + this.id).on('hide.bs.modal', function () {
myAlert.callback();
});
this.init = null;
},
callback: $.noop,
close: function () {
$('#' + myAlert.id).modal('hide');
},
open: function (options) {
if (!this.id) {
this.id = utils.uuid.uuid();
$('body').append(utils.template.nano(this.template, {id: this.id}));
$('#' + this.id + ' button.btn-primary').on('click', myAlert.close);
}
var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
this.callback = setting.callback ? setting.callback : $.noop;
$('h4.modal-title', dom).text(setting.title);
$('div.modal-body', dom).html(setting.body);
document.activeElement && $(document.activeElement).blur();
dom.modal({backdrop: 'static', show: true});
this.init && this.init();
}
}
var myConfirm = {
id: null,
template: '<div class="modal fade" id="{id}" role="dialog" aria-hidden="true" style="width: 360px"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
settings: {
title: '消息提示',
body: '确定继续'
},
callback: $.noop,
result: false,
init: function () {
$('#' + this.id).on('hide.bs.modal', function () {
myConfirm.callback(myConfirm.result);
});
this.init = null;
},
close: function () {
$('#' + myConfirm.id).modal('hide');
},
open: function (options) {
if (!this.id) {
this.id = utils.uuid.uuid();
$('body').append(utils.template.nano(this.template, {id: this.id}));
$('#' + this.id + ' button.btn-primary').on('click', function () {
myConfirm.result = true;
myConfirm.close();
});
}
var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
$('h4.modal-title', dom).text(setting.title);
$('div.modal-body', dom).html(setting.body);
this.callback = setting.callback ? setting.callback : $.noop;
this.result = false;
document.activeElement && $(document.activeElement).blur();
dom.modal({backdrop: 'static', show: true});
this.init && this.init();
}
}
测试页面
window.onload = function(){
utils.modal.myAlert("提示","操作失败!",function(){
alert("111");
});
utils.modal.myConfirm("提示","确定删除吗",function(flag){
alert(flag);
});
};
整体代码,可直接复制使用,css 需要的可以微调
var utils = {};
utils.uuid= {
uuid:function(){
var d = new Date().getTime();
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){
var r = (d+Math.random()*16)%16 |0; // Math.random()*16 随机产生0-16之间的小数 % 模运算即取余
d = Math.floor(d/16); //round()四舍五入;floor()向上取整;ceil()向下取整;
return (c = 'x'?r:(r &0x7 |0x8)).toString(16);
});
return uuid;
}
};
utils.modal = {
/**
* myAlert
* @param title 标题 不填则默认
* @param body 内容
* @param callback 回调函数
*/
myAlert: function () {
var settings = resolveModal.apply({}, arguments);
myAlert.open(settings);
},
/**
* myConfirm
* @param title 标题
* @param body 内容
* @param callback 回调函数
*/
myConfirm: function () {
var settings = resolveModal.apply({}, arguments);
myConfirm.open(settings);
}
};
var resolveModal = function () {//解析调用时的参数,并返回
var settings = null;
if (arguments.length == 1) {//仅一个参数
if ($.type(arguments[0]) == 'string') {
settings = {
body: arguments[0]
}
} else if ($.type(arguments[0]) == 'object') {
settings = arguments[0];
} else if ($.type(arguments[0]) == 'function') {
settings = {
callback: arguments[0]
}
}
} else if (arguments.length == 2) {//两个参数
if ($.type(arguments[1]) == 'function') {
settings = {
body: arguments[0],
callback: arguments[1]
}
} else {
settings = {
title: arguments[0],
body: arguments[1]
}
}
} else if (arguments.length == 3) {//三个参数
settings = {
title: arguments[0],
body: arguments[1],
callback: arguments[2]
}
}
return settings;
};
var myAlert = {
id: null,
template: '<div class="modal fade" id="{id}" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
settings: {
title: '消息提示',
body: '消息提示'
},
init: function () {
$('#' + this.id).on('hide.bs.modal', function () {
myAlert.callback();
});
this.init = null;
},
callback: $.noop,
close: function () {
$('#' + myAlert.id).modal('hide');
},
open: function (options) {
if (!this.id) {
this.id = utils.uuid.uuid();
$('body').append(utils.template.nano(this.template, {id: this.id}));
$('#' + this.id + ' button.btn-primary').on('click', myAlert.close);
}
var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
this.callback = setting.callback ? setting.callback : $.noop;
$('h4.modal-title', dom).text(setting.title);
$('div.modal-body', dom).html(setting.body);
document.activeElement && $(document.activeElement).blur();
dom.modal({backdrop: 'static', show: true});
this.init && this.init();
}
}
var myConfirm = {
id: null,
template: '<div class="modal fade" id="{id}" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
settings: {
title: '消息提示',
body: '确定继续'
},
callback: $.noop,
result: false,
init: function () {
$('#' + this.id).on('hide.bs.modal', function () {
myConfirm.callback(myConfirm.result);
});
this.init = null;
},
close: function () {
$('#' + myConfirm.id).modal('hide');
},
open: function (options) {
if (!this.id) {
this.id = utils.uuid.uuid();
$('body').append(utils.template.nano(this.template, {id: this.id}));
$('#' + this.id + ' button.btn-primary').on('click', function () {
myConfirm.result = true;
myConfirm.close();
});
}
var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
$('h4.modal-title', dom).text(setting.title);
$('div.modal-body', dom).html(setting.body);
this.callback = setting.callback ? setting.callback : $.noop;
this.result = false;
document.activeElement && $(document.activeElement).blur();
dom.modal({backdrop: 'static', show: true});
this.init && this.init();
}
}
utils.template = {
// JS模板工具 https://github.com/trix/nano
/**
* @param template 静态的模板,模型使用{object.name}的形式
* @param data 填充的数据对象
* @returns {XML|string|void}
*/
nano: function (template, data) {
return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
var keys = key.split("."), v = data[keys.shift()];
for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
return (typeof v !== "undefined" && v !== null) ? v : "";
});
}
};
5.简单的判别浏览器(ie/firefox/chrome,新出的win10的edge浏览器在这里匹配不成功,显示的是chrome浏览器,需要的话需要重写)
edge的navigator.userAgent:mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/46.0.2486.0 safari/537.36 edge/13.10586
utils.browser ={
isIE: function () {
return /msie/.test(navigator.userAgent.toLowerCase()) || /rv:([\d.]+)\) like gecko/.test(navigator.userAgent.toLowerCase());
},
isFirefox: function () {
return /firefox/.test(navigator.userAgent.toLowerCase());
},
isChrome: function () {
return /chrome/.test(navigator.userAgent.toLowerCase());
},
get: function () {
var browser = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/rv:([\d.]+)\) like gecko/)) ? browser.ie = s[1] : (s = ua.match(/msie ([\d.]+)/)) ? browser.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? browser.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? browser.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? browser.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? browser.safari = s[1] : 0;
return browser;
}
}
6.订阅/发布/取消订阅模式(观察者模式)
jquery版
(function ($) { //jquery私有作用域
var o = $({});
$.subscribe = function () {
o.on.apply(o, arguments);
};
$.unsubscribe = function () {
o.off.apply(o, arguments);
};
$.publish = function () {
o.trigger.apply(o, arguments);
};
}(jQuery));
页面调用
·订阅一个事件,函数中执行代码,接下来如果想调用这个事件,则直接发布即可,如果想取消这个订阅事件,则取消即可。
<%--
Created by IntelliJ IDEA.
User: 111
Date: 2016/2/10
Time: 11:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCtype html>
<html>
<head>
<%--<script type="text/javascript" src="../public/js/amd_test.js"></script>--%>
<link rel="stylesheet" href="../public/lib/bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="../public/lib/jquery/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="../public/js/utils.js"></script>
<script type="text/javascript" src="../public/lib//bootstrap/js/bootstrap.min.js"></script>
<title></title>
<script type="text/javascript">
window.onload = function(){
utils.quick.click({
btn:function(){
$.publish("/test/data");
$.unsubscribe("");
}
})
$.subscribe("/test/data",function(){
alert("subscribe");
});
};
</script>
</head>
<body>
<div>
<button data-click="btn">点击</button>
</div>
</body>
</html>
7.对字符串判断的一些util类
utils.string = {
trim: function (str) {
return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '');
},
isEmpty: function (str) {
return (!str || 0 === str.length);
},
isNotEmpty: function (str) {
return !this.isEmpty(str);
},
isBlank: function (str) {
return (!str || 0 === this.trim(str).length);
},
isNotBlank: function (str) {
return !this.isBlank(str);
},
startwith:function(data,str){
if(str==null||str==""||data == null ||data.length==0||str.length>data.length)
return false;
if(data.substr(0,str.length)==str)
return true;
else
return false;
return true;
},
endwith:function(data,str){
if(str==null||str==""||data == null ||data.length==0||str.length>data.length)
return false;
if(data.substring(data.length-str.length)==str)
return true;
else
return false;
return true;
}
};
8.ajax的get/post请求
utils.js
utils.myAjax ={
post: function () {
var list = resolveAjax(arguments);
var settings = {
url: list[0],
dataType: 'json',
type: 'POST',
data: list[1],
cache: false
};
$.ajax(settings).done(list[2]).fail(function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 200 && XMLHttpRequest.responseText.indexOf('<title>CAS – Central Authentication Service</title>') > 0) {
utils.modal.alert('登录超时', function () {
location.reload();
});
} else {
list[3](XMLHttpRequest, textStatus, errorThrown)
}
});
},
get: function () {
var list = resolveAjax(arguments);
var settings = {
url: list[0],
dataType: 'json',
type: 'GET',
data: list[1],
cache: false
};
$.ajax(settings).done(list[2]).fail(function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 401) {
location.reload();
}
else {
list[3](XMLHttpRequest, textStatus, errorThrown)
}
});
}
};
var resolveAjax = function (arg) {
if (!arg.length) {
throw 'URL不能为空'
}
var result = [];
for (var i = 0; i < arg.length; i++) {
result.push(arg[i]);
}
if ($.type(result[1]) == 'function') {
result.splice(1, 0, '');
}
if (!result[3]) {
result.push($.noop);
}
return result;
};
页面调用:
utils.myAjax.post("../test/data",{},function(){
alert("11");
});