common.js 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043
  1. /**
  2. * 公共函数库,主要是一些JS工具函数,各种插件的公共设置
  3. * @author HenryYan
  4. */
  5. (function($) {
  6. $.common = {};
  7. //-- 初始化方法 --//
  8. _initFunction();
  9. //-- 窗口工具 --//
  10. $.common.window = {
  11. //-- 获得最上层的window对象 --//
  12. getTopWin: function() {
  13. if (parent) {
  14. var tempParent = parent;
  15. while (true) {
  16. $.common.plugin$.common.plugin
  17. if (tempParent.parent) {
  18. if (tempParent.parent == tempParent) {
  19. break;
  20. }
  21. tempParent = tempParent.parent;
  22. } else {
  23. break;
  24. }
  25. }
  26. return tempParent;
  27. } else {
  28. return window;
  29. }
  30. },
  31. // 获取可见区域的宽度
  32. getClientWidth: function() {
  33. return document.documentElement.clientWidth - 10;
  34. },
  35. // 获取可见区域的高度
  36. getClientHeight: function(options) {
  37. var defaults = {
  38. autoSuit: true, // 自动适应高度,因为在firefox下面不减10会出现滚动条
  39. autoSuitValue: -13
  40. };
  41. options = $.extend({}, defaults, options);
  42. if (options.autoSuit) {
  43. return document.documentElement.clientHeight + options.autoSuitValue;
  44. } else {
  45. return document.documentElement.clientHeight;
  46. }
  47. }
  48. };
  49. /*******************************************/
  50. /** jqGrid插件--开始 **/
  51. /*******************************************/
  52. var _plugin_jqGrid = {
  53. prmNames: {
  54. page: 'page.pageNo',
  55. rows: 'page.pageSize',
  56. sort: 'page.orderBy',
  57. order: 'page.order',
  58. search: 'page.search',
  59. id: 'jqid'
  60. },
  61. jsonReader: {
  62. root: 'page.result',
  63. page: 'page.pageNo',
  64. total: 'page.totalPages',
  65. records: 'page.totalCount',
  66. repeatitems: false
  67. },
  68. pager: {
  69. add: true,
  70. edit: true,
  71. view: true,
  72. del: true,
  73. addtext: '新增',
  74. edittext: '编辑',
  75. viewtext: '查看',
  76. deltext: '删除',
  77. searchtext: '查询',
  78. refreshtext: '刷新'
  79. },
  80. navGrid: {
  81. /**
  82. * 显示对话框字段,如果不指定fields参数显示所有隐藏的字段
  83. * @param {Object} formid jqGrid表单ID
  84. * @param {Object} includes 要显示的字段名称,规则tr_字段
  85. * @param {Object} excludes 要显示的字段名称,规则tr_字段
  86. */
  87. showAllField: function(formid, includes, excludes) {
  88. if (includes && includes.length > 0) {
  89. $.each(includes, function(i, n) {
  90. // 编辑时
  91. // 查看时
  92. $('tr[id=trv_' + n + ']', formid).show();
  93. });
  94. return;
  95. }
  96. if (excludes && excludes.length > 0) {
  97. // 编辑时
  98. var $trs = $('tr[id^=tr_].FormData', formid);
  99. $.each($trs, function() {
  100. var fieldName = $(this).attr('id').substring(3);
  101. if ($.inArray(fieldName, excludes) == -1) {
  102. $(this).show();
  103. }
  104. });
  105. // 查看时
  106. $trs = $('tr[id^=trv].FormData', formid);
  107. $.each($trs, function() {
  108. var fieldName = $(this).attr('id').substring(4);
  109. if ($.inArray(fieldName, excludes) == -1) {
  110. $(this).show();
  111. }
  112. });
  113. return;
  114. }
  115. $('tr[id^=tr].FormData', formid).show();
  116. }
  117. },
  118. //-- jqGrid工具栏按钮 --//
  119. navButtonAdd: {
  120. //-- 显示/隐藏字段 --//
  121. setColumns: {
  122. caption: "字段",
  123. title: "设置列表显示的字段",
  124. buttonicon: "ui-icon-wrench",
  125. onClickButton: function() {
  126. $(this).jqGrid('columnChooser');
  127. }
  128. }
  129. },
  130. //-- 搜索比较符号 --/
  131. search: {
  132. text: ['cn', 'eq', 'ne'],
  133. select: ['eq', 'ne'],
  134. integer: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
  135. 'float': ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
  136. date: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
  137. // 初始化My97日期组件
  138. initDate: function(settings) {
  139. $(settings.elem).addClass('Wdate');
  140. $(settings.elem).click(function() {
  141. WdatePicker();
  142. });
  143. }
  144. },
  145. //-- 格式化 值--//
  146. formatter: {
  147. // 日期类型,例如:2010-08-19
  148. date: function(cellvalue, options, cellobject) {
  149. if (cellvalue == null || cellvalue == 'null')
  150. return "";
  151. else {
  152. if (cellvalue.length >= 10) {
  153. return cellvalue.substring(0, 10);
  154. } else {
  155. return cellvalue;
  156. }
  157. }
  158. },
  159. // 日期和时间类型,例如:2010-08-19 12:12:13
  160. datetime: function(cellvalue, options, cellobject) {
  161. if (cellvalue == null || cellvalue == 'null') {
  162. return "";
  163. } else {
  164. var preCellValue = cellvalue.substring(0, 10);
  165. var postCellvalue = cellvalue.substring(11, cellvalue.length);
  166. return preCellValue + " " + postCellvalue;
  167. }
  168. },
  169. trueOrfalse: function(cellvalue, options, cellobject) {
  170. if (cellvalue == null ||
  171. cellvalue == 'null' ||
  172. cellvalue == 0)
  173. return "否";
  174. return "是";
  175. },
  176. // 使用图片显示是否值,是显示图片,否不显示任何值
  177. trueOrFalseImg: function(cellvalue, options, cellobject) {
  178. if (cellvalue == null ||
  179. cellvalue == 'null' ||
  180. cellvalue == 0)
  181. return "";
  182. var okImgPath = $.common.custom.getCtx() + "/images/tip/ok.gif";
  183. return "<img src='" + okImgPath + "'/>";
  184. },
  185. float2precent: function(cellvalue, options, cellobject) {
  186. if (cellvalue == null || cellvalue == 'null')
  187. return "";
  188. return cellvalue * 100 + '%';
  189. }
  190. },
  191. form: {
  192. // 表单必填标志
  193. must: function() {
  194. return "<span class='must'>*</span>";
  195. },
  196. mustTip: "带 <span class='must'>*</span> 为必填(选)项。",
  197. // 添加设置
  198. add: {
  199. modal: true,
  200. closeAfterAdd: false,
  201. recreateForm: true,
  202. closeOnEscape: true,
  203. savekey: [true, 13],
  204. navkeys: [true, 38, 40],
  205. bottominfo: "带 <span class='must'>*</span> 为必填(选)项。",
  206. onInitializeForm: function(formObj) {
  207. // 鼠标划过的时候高亮当前行
  208. $('tr.FormData', formObj).hover(function() {
  209. $(this).addClass('ui-state-hover');
  210. }, function() {
  211. $(this).removeClass('ui-state-hover');
  212. }).click(function() {
  213. $('tr.FormData', formObj).removeClass('ui-state-active');
  214. $(this).addClass('ui-state-active');
  215. });
  216. // 如果对话框的高度超过了列表的高度则出现滚动条,延迟20毫秒执行
  217. setTimeout(function() {
  218. var formDialogHeight = $(formObj).parents('.ui-jqdialog').height();
  219. var formDialogWidth = $(formObj).parents('.ui-jqdialog').width();
  220. var listId = $(formObj).attr('id').replace('FrmGrid_', '');
  221. var subGridLength = $('#gview_' + listId).parents('td.subgrid-data').length;
  222. if (subGridLength > 0) {
  223. $(formObj).parents('.ui-jqdialog').css({
  224. top: 0,
  225. left: 0
  226. });
  227. return;
  228. }
  229. // 设置参数autoSizeForm时不自动调整表单对话框高度
  230. if ($('#listId').jqGrid('getGridParam', 'autoSizeForm') === true) {
  231. var gridHeight = $('#gview_' + listId).height();
  232. if (formDialogHeight > gridHeight) {
  233. $(formObj).height(gridHeight - $(formObj).next('.EditTable').height() - 30);
  234. }
  235. }
  236. }, 20);
  237. },
  238. onClose: function(formObj) {
  239. try {
  240. $('.ui-tooltip-red').qtip('destroy');
  241. } catch (e) {
  242. }
  243. }
  244. },
  245. // 编辑设置
  246. edit: {
  247. modal: true,
  248. closeAfterEdit: false,
  249. recreateForm: true,
  250. closeOnEscape: true,
  251. savekey: [true, 13],
  252. navkeys: [true, 38, 40],
  253. bottominfo: "带 <span class='must'>*</span> 为必填(选)项。",
  254. onInitializeForm: function(formObj) {
  255. // 鼠标划过的时候高亮当前行
  256. $('tr.FormData', formObj).hover(function() {
  257. $(this).addClass('ui-state-hover');
  258. }, function() {
  259. $(this).removeClass('ui-state-hover');
  260. }).click(function() {
  261. $('tr.FormData', formObj).removeClass('ui-state-active');
  262. $(this).addClass('ui-state-active');
  263. });
  264. // 如果对话框的高度超过了列表的高度则出现滚动条,延迟20毫秒执行
  265. setTimeout(function() {
  266. var formDialogHeight = $(formObj).parents('.ui-jqdialog').height();
  267. var listId = $(formObj).attr('id').replace('FrmGrid_', '');
  268. var subGridLength = $('#gview_' + listId).parents('td.subgrid-data').length;
  269. if (subGridLength > 0) {
  270. $(formObj).parents('.ui-jqdialog').css({
  271. top: 0,
  272. left: 0
  273. });
  274. return;
  275. }
  276. var gridHeight = $('#gview_' + listId).height();
  277. if (formDialogHeight > gridHeight) {
  278. $(formObj).height(gridHeight - $(formObj).next('.EditTable').height() - 30);
  279. }
  280. }, 20);
  281. },
  282. onClose: function(formObj) {
  283. try {
  284. $('.ui-tooltip-red').qtip('destroy');
  285. } catch (e) {
  286. }
  287. }
  288. },
  289. // 删除设置
  290. del: {
  291. },
  292. // 搜索设置
  293. search: {
  294. multipleSearch: true,
  295. showQuery: false,
  296. multipleGroup: false,
  297. sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'in', 'ni', 'ew', 'en', 'cn', 'nc', 'nu', 'nn'],
  298. afterRedraw: function() {
  299. // 新版本已经实现了此功能
  300. return;
  301. // 从下拉况中选择保存过的查询条件
  302. var savedFilters = {
  303. '医保在上海年龄20-30之间': {
  304. "groupOp": "AND",
  305. "rules": [{
  306. "field": "age",
  307. "op": "ge",
  308. "data": "20"
  309. }, {
  310. "field": "age",
  311. "op": "le",
  312. "data": "30"
  313. }, {
  314. field: "medicareAddress",
  315. "op": "eq",
  316. "data": "上海"
  317. }]
  318. },
  319. 年龄20岁以上: {
  320. "groupOp": "OR",
  321. "rules": [{
  322. "field": "age",
  323. "op": "le",
  324. "data": "20"
  325. }]
  326. }
  327. };
  328. $('.opsel').before("<select class='saved-filters' title='已保存搜索条件'><option>--请选择--</option></select>" +
  329. "<input id='filterName' size='15' style='display:none' title='输入名称后可以保存搜索条件' />");
  330. $.each(savedFilters, function(i, v) {
  331. $("<option />", {
  332. value: i,
  333. text: i
  334. }).appendTo('.saved-filters');
  335. });
  336. $('.saved-filters').unbind('change').bind('change', function() {
  337. // 1、删除所有条件
  338. $('#fbox_list_reset').trigger('click');
  339. // 2、设置条件
  340. var filterName = $('option:selected', this).val();
  341. var groupOp = savedFilters[filterName].groupOp;
  342. var rules = savedFilters[filterName].rules;
  343. $('.opsel option[value=' + groupOp + ']').attr('selected', true);
  344. for (var i = 0; i < rules.length; i++) {
  345. if ($('.columns').length < rules.length) {
  346. $('.add-rule').trigger('click');
  347. }
  348. $('.columns:eq(' + i + ') select option[value=' + rules[i].field + ']').attr('selected', true).trigger('change');
  349. $('.operators:eq(' + i + ') select option[value=' + rules[i].op + ']').attr('selected', true);
  350. $('.data:eq(' + i + ') *').val(rules[i].data)
  351. }
  352. // 3、选中当前条件
  353. $('.saved-filters option:[text=' + filterName + ']').attr('selected', true);
  354. });
  355. },
  356. afterShowSearch: function() {
  357. /*
  358. * 添加回车键搜索功能
  359. */
  360. $('.ui-searchFilter .data *').keydown(function(e) {
  361. if (e.which == 13 || e.which == 10) {
  362. $('.ui-searchFilter tfoot .ui-search').trigger('click');
  363. }
  364. });
  365. /*
  366. * hack: 搜索类型有select时点击重置按钮后无效
  367. */
  368. $('.ui-reset').bind('click', function() {
  369. $('.data').find('.vdata').removeClass('vdata');
  370. $('.data').find('select').hide();
  371. $('.data').find('.default').addClass('vdata').show();
  372. // 比较符号重置为默认(第一个)
  373. $('.ops').find('select').hide();
  374. $('.ops').find('.field0').show();
  375. });
  376. }
  377. },
  378. // 查看设置
  379. view: {
  380. beforeShowForm: function(formid) {
  381. $.common.plugin.jqGrid.navGrid.showAllField(formid);
  382. setTimeout(function() {
  383. // 隐藏编辑按钮
  384. $('#trv_options').hide();
  385. // 如果对话框的高度超过了列表的高度则出现滚动条,延迟20毫秒执行
  386. var formDialogHeight = $(formid).parents('.ui-jqdialog').height();
  387. var listId = $(formid).attr('id').replace('ViewGrid_', '');
  388. var gridHeight = $('#gview_' + listId).height();
  389. if (formDialogHeight > gridHeight) {
  390. $(formid).height($.common.window.getClientHeight() - $(formid).next('.EditTable').height() - 38);
  391. }
  392. }, 10);
  393. }
  394. }
  395. },
  396. /**
  397. * 改变窗口大小的时候自动根据iframe大小设置jqGrid列表宽度和高度
  398. * 参数说明:{
  399. * enableAutoResize : 是否开启自动高度和宽度调整开关
  400. * dataGrid : jqGrid数据列表的ID
  401. * callback : 计算完dataGrid需要的高度和宽度后的回调函数
  402. * width : 默认为iframe的宽度,如果指定则设置为指定的宽度
  403. * height : 默认为iframe的高度,如果指定则设置为指定的高度
  404. * beforeAutoResize : 窗口大小调整时自动设置之前
  405. * afterAutoResize : 窗口大小调整时自动设置之后
  406. * }
  407. */
  408. autoResize: function(options) {
  409. var defaults = {
  410. gridContainer: 'body',
  411. filterToolbar: false,
  412. groupHeaders: false,
  413. enableAutoResize: true,
  414. beforeAutoResize: null,
  415. afterAutoResize: null
  416. };
  417. options = $.extend({}, defaults, options);
  418. // 第一次调用
  419. var size = getWidthAndHeigh();
  420. if ($.isFunction(options.callback)) {
  421. options.callback(size);
  422. setToolbarHeight();
  423. }
  424. // 窗口大小改变的时候
  425. if (options.enableAutoResize === true) {
  426. if ($.isFunction(options.beforeAutoResize)) {
  427. options.beforeAutoResize();
  428. }
  429. window.onresize = function() {
  430. var size = getWidthAndHeigh(true);
  431. $(options.dataGrid).jqGrid('setGridHeight', size.height).jqGrid('setGridWidth', size.width);
  432. setToolbarHeight();
  433. if ($.isFunction(options.afterAutoResize)) {
  434. options.afterAutoResize(size);
  435. }
  436. };
  437. }
  438. // 根据浏览器不同设置工具栏的高度
  439. function setToolbarHeight() {
  440. // 根据浏览器不同设置工具栏的高度
  441. if ($.common.browser.isIE() && options.toolbarHeight) {
  442. if (options.toolbarHeight.top && options.toolbarHeight.top.ie) {
  443. $('#t_' + options.dataGrid.substr(1)).height(options.toolbarHeight.top.ie);
  444. }
  445. if (options.toolbarHeight.bottom && options.toolbarHeight.bottom.ie) {
  446. $('#tb_' + options.dataGrid.substr(1)).height(options.toolbarHeight.bottom.ie);
  447. }
  448. }
  449. }
  450. // 获取iframe大小
  451. function getWidthAndHeigh(resize) {
  452. var hasToolbar = !options.toolbar ? false : options.toolbar[0];
  453. if (hasToolbar) {
  454. var toolbarType = options.toolbar[1];
  455. if (!toolbarType) {
  456. alert('请设置工具栏的属性,toolbar : [true, [top, both, bottom]]');
  457. }
  458. }
  459. // 根据列表的容器设置宽度和高度
  460. var clientHeight = options.gridContainer == 'body' ? document.documentElement.clientHeight : $(options.gridContainer).get(0).clientHeight;
  461. var clientWidth = options.gridContainer == 'body' ? document.documentElement.clientWidth : $(options.gridContainer).get(0).clientWidth;
  462. var iframeHeight = !options.height ? clientHeight : options.height;
  463. var iframeWidth = !options.width ? clientWidth : options.width;
  464. // chrome
  465. if ($.common.browser.isChrome()) {
  466. if (hasToolbar) {
  467. if (toolbarType == 'top' || toolbarType == 'bottom') {
  468. iframeWidth -= 4;
  469. iframeHeight -= 120;
  470. } else if (toolbarType == 'both') {
  471. iframeWidth -= 14;
  472. iframeHeight -= 140;
  473. }
  474. } else {
  475. iframeWidth -= 4;
  476. iframeHeight -= 85;
  477. }
  478. } else if ($.common.browser.isMozila() || $.common.browser.isOpera()) {
  479. if (hasToolbar) {
  480. if (toolbarType == 'top' || toolbarType == 'bottom') {
  481. iframeWidth -= 3;
  482. iframeHeight -= 118;
  483. } else if (toolbarType == 'both') {
  484. iframeWidth -= 12;
  485. iframeHeight -= 145;
  486. }
  487. } else {
  488. iframeWidth -= 4;
  489. iframeHeight -= 85;
  490. }
  491. } else {
  492. if (hasToolbar) {
  493. if (toolbarType == 'top' || toolbarType == 'bottom') {
  494. if ($.common.browser.isIE() && options.toolbarHeight) {
  495. if (options.toolbarHeight.top && options.toolbarHeight.top.ie) {
  496. // 减去jqGrid的t_list默认高度和IE的兼容高度
  497. iframeHeight -= (options.toolbarHeight.top.ie - 21) - 15;
  498. }
  499. }
  500. iframeHeight -= 123;
  501. iframeWidth -= 6;
  502. setTimeout(function() {
  503. // 设置上方的toolbar
  504. $('#t_' + options.dataGrid.substr(1)).width(iframeWidth - 11);
  505. });
  506. } else if (toolbarType == 'both') {
  507. iframeWidth -= 6;
  508. iframeHeight -= 156;
  509. setTimeout(function() {
  510. // 设置上方的toolbar
  511. $('#t_' + options.dataGrid.substr(1)).width(iframeWidth - 11);
  512. });
  513. }
  514. } else {
  515. iframeWidth -= 6;
  516. iframeHeight -= 85;
  517. }
  518. }
  519. // 是否有搜索工具条
  520. if (options.filterToolbar) {
  521. iframeHeight -= 23;
  522. }
  523. // 是否开启标头分组
  524. if (options.groupHeaders) {
  525. iframeHeight -= 22;
  526. }
  527. return {
  528. width: iframeWidth,
  529. height: iframeHeight
  530. };
  531. }
  532. },
  533. // jqGrid快捷键支持
  534. keys: {
  535. savekey: [true, 13],
  536. navkeys: [true, 38, 40]
  537. },
  538. // checkbox工具
  539. checkbox: {
  540. /**
  541. * 获取选中的checkbox
  542. * @param {Object} listId
  543. */
  544. getChecked: function(listId) {
  545. var chks = $('#' + listId + ' :checkbox[name!=cb_' + listId + ']:checked');
  546. $.each(chks, function() {
  547. var rowId = $(this).parents('tr').attr('id');
  548. $(this).data('rowId', rowId);
  549. });
  550. return chks;
  551. },
  552. /**
  553. * 获取选中的记录ID,以逗号分隔
  554. * @param {Object} listObj 列表对象
  555. * @param {Object} dealFn 过滤函数,如果加入选中的ID那么return true,否则return false
  556. */
  557. convertToString: function(listObj, dealFn) {
  558. var chks = $(listObj + ' :checkbox[name^=jqg_list]:checked');
  559. var ids = "";
  560. $.each(chks, function(i, n) {
  561. var tempId = $(this).attr('name').replace('jqg_list_', '');
  562. // 调用过滤函数
  563. if ($.isFunction(dealFn)) {
  564. var useId = dealFn(tempId);
  565. if (useId) {
  566. ids += tempId + ",";
  567. }
  568. } else {
  569. ids += tempId + ",";
  570. }
  571. });
  572. if (ids.indexOf(',') != -1) {
  573. ids = ids.substring(0, ids.length - 1);
  574. }
  575. return ids;
  576. }
  577. },
  578. /**
  579. * jqgrid列表的gridComplete方法
  580. * @param {Object} listId 列表ID
  581. * @param {Object} callback 回调函数
  582. */
  583. gridComplete: function(listId, callback) {
  584. if (listId.substring(0, 1) == '#') {
  585. listId = listId.substring(1);
  586. }
  587. if (!$('#' + listId).data('gridComplete')) {
  588. setTimeout(function() {
  589. // 修复IE下鼠标移动到按钮后格式会乱的问题
  590. $('#' + listId + ' td[$=_left] .ui-pg-button').each(function() {
  591. $(this).width($(this).width() + 3);
  592. });
  593. if ($.isFunction(callback)) {
  594. callback(listId);
  595. }
  596. $('#' + listId).data('gridComplete', true);
  597. }, 500);
  598. }
  599. },
  600. /**
  601. * 顶部的搜索条
  602. */
  603. filterToolbar: {
  604. settings: {
  605. stringResult: true,
  606. defaultSearch: 'cn'
  607. }
  608. },
  609. /**
  610. * 标头分组
  611. */
  612. groupHeaders: {
  613. settings: {
  614. useColSpanStyle: true
  615. }
  616. },
  617. /**
  618. * 解决列冻结时因为高度不一致
  619. * @param {Object} listId
  620. */
  621. setColumnHeighForFrozen: function(listId, timeout) {
  622. setTimeout(function() {
  623. $(listId + '_frozen tr').each(function() {
  624. var rowId = $(this).attr('id');
  625. var frozenTdHeight = parseFloat($('td:first', this).height());
  626. var normalHeight = parseFloat($(listId + ' #' + $(this).attr('id')).find('td:first').height());
  627. if (frozenTdHeight - normalHeight > 0) {
  628. $('#' + rowId + ' td', listId).height(frozenTdHeight);
  629. } else if (frozenTdHeight - normalHeight < 0) {
  630. $('td', this).height(normalHeight);
  631. }
  632. });
  633. }, timeout || 10);
  634. },
  635. /**
  636. * 多选改进双击切换状态
  637. * @param {Object} listId
  638. */
  639. dealMultiselect: function(listId) {
  640. // 高亮显示选中
  641. $('.jqgrow input[type=checkbox]', listId).change(function() {
  642. if ($(this).attr('checked') == 'checked') {
  643. $(this).parents('tr').addClass('ui-state-highlight');
  644. } else {
  645. $(this).parents('tr').removeClass('ui-state-highlight');
  646. }
  647. });
  648. // 双击选中
  649. $('.jqgrow', listId).off('dblclick').on('dblclick', function(e) {
  650. var s = $(this).find('input[type=checkbox]').attr('checked');
  651. if (s == 'checked') {
  652. $(this).find('input[type=checkbox]').attr('checked', false).trigger('change');
  653. } else {
  654. $(this).find('input[type=checkbox]').attr('checked', true).trigger('change');
  655. }
  656. });
  657. },
  658. /**
  659. * 查询条件工具
  660. */
  661. search: {
  662. queryString: function(listId) {
  663. var query = "";
  664. $('table[aria-labelledby=gbox_' + listId + '] .ui-search-toolbar :input').each(function() {
  665. if ($(this).val()) {
  666. if (query.length > 0) {
  667. query += " and ";
  668. }
  669. query += $(this).attr('name') + '=' + $(this).val();
  670. }
  671. });
  672. return query;
  673. }
  674. }
  675. };
  676. /**
  677. * jqGrid公共参数,供集成使用
  678. */
  679. _plugin_jqGrid.settings = function(options) {
  680. var multiselect = $('body').data('flowDataType_list') == 'unsigned' || $('body').data('flowDataType_list') == 'todo';
  681. return {
  682. datatype: "json",
  683. prmNames: _plugin_jqGrid.prmNames,
  684. jsonReader: _plugin_jqGrid.jsonReader,
  685. width: options.size.width,
  686. height: options.size.height,
  687. rowNum: options.rowNum || 20,
  688. rowList: options.rowList || [10, 15, 20, 30, 40, 50, 100],
  689. pager: options.pager || '#pager',
  690. viewrecords: true,
  691. rownumbers: true,
  692. multiselect: multiselect,
  693. //subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e" },
  694. loadComplete: function(data) {
  695. if (data) {
  696. $('body').data('jqgridData_' + this.id, data);
  697. var idToDataMap = {};
  698. if (data.page && data.page.result) {
  699. $.each(data.page.result, function() {
  700. idToDataMap[this.id] = this;
  701. });
  702. }
  703. $('body').data('jqgridResult_' + this.id, idToDataMap);
  704. var afterCall = $('#' + this.id).jqGrid('getGridParam', 'afterLoadComplete');
  705. if ($.isFunction(afterCall)) {
  706. afterCall.call(this, this.id, data);
  707. }
  708. }
  709. },
  710. loadError: function(xhr, st, err) {
  711. //alert("很抱歉,出错了!\n错误类型: " + st + "; 错误内容: "+ xhr.status + " " + xhr.statusText);
  712. var s = "未知";
  713. if (xhr.status == 404) {
  714. s = "找不到数据源";
  715. } else if (xhr.status == 500) {
  716. s = "服务器内部错误";
  717. } else if (xhr.responseText == '_login_timeout') {
  718. s = "登录超时!";
  719. }
  720. alert("很抱歉,数据加载失败!\n错误类型: " + s);
  721. }
  722. };
  723. };
  724. /*******************************************/
  725. /** jqGrid插件--结束 **/
  726. /*******************************************/
  727. /*******************************************/
  728. /** jquery.validator插件--开始 **/
  729. /*******************************************/
  730. var _plugin_validator = {
  731. // 错误信息显示位置
  732. errorPlacement: function(error, element) {
  733. // Set positioning based on the elements position in the form
  734. var elem = $(element), corners = ['right center', 'left bottom'], flipIt = elem.parents('span.right').length > 0;
  735. // Check we have a valid error message
  736. if (!error.is(':empty')) {
  737. // Apply the tooltip only if it isn't valid
  738. elem.filter(':not(.valid)').qtip({
  739. overwrite: false,
  740. content: error,
  741. position: {
  742. my: corners[flipIt ? 0 : 1],
  743. at: corners[flipIt ? 1 : 0],
  744. viewport: $(window),
  745. adjust: {
  746. x: 2,
  747. y: 10
  748. }
  749. },
  750. show: {
  751. event: false,
  752. ready: true
  753. },
  754. hide: false,
  755. style: {
  756. classes: 'ui-tooltip-red validator-error'
  757. },
  758. events: {
  759. show: function(event, api) {
  760. // 设置qtip绑定的表单元素
  761. $(this).data('elem', elem);
  762. }
  763. }
  764. }).qtip('option', 'content.text', error);
  765. } else {
  766. elem.qtip('destroy');
  767. }
  768. },
  769. success: function(label) {
  770. label.html("&nbsp;").addClass("checked");
  771. var forEle = label.attr('for');
  772. if (forEle == 'phone') {
  773. if ($.isFunction(callback)) {
  774. callback();
  775. }
  776. }
  777. }
  778. };
  779. /*******************************************/
  780. /** jquery.validator插件--结束 **/
  781. /*******************************************/
  782. /*******************************************/
  783. /** jQuery UI--开始 **/
  784. /*******************************************/
  785. var _plugin_jqui = {
  786. /**
  787. * 按钮相关
  788. */
  789. button: {
  790. onOff: function(options) {
  791. var defaults = {
  792. btnText: false // text
  793. };
  794. options = $.extend({}, defaults, options);
  795. var dlgButton = $('.ui-dialog-buttonpane button');
  796. if (options.btnText) {
  797. // TODO 查询优化,兼容有相同文字的情况
  798. dlgButton = $('.ui-button-text:contains(' + options.btnText + ')').parent();
  799. }
  800. if (options.enable) {
  801. dlgButton.attr('disabled', '');
  802. dlgButton.removeClass('ui-state-disabled');
  803. } else {
  804. dlgButton.attr('disabled', 'disabled');
  805. dlgButton.addClass('ui-state-disabled');
  806. }
  807. }
  808. },
  809. /**
  810. * 对话框相关
  811. */
  812. dialog: {
  813. event: {
  814. close: function() {
  815. $(this).dialog('close');
  816. }
  817. },
  818. /**
  819. * 按钮相关方法
  820. */
  821. button: {
  822. /**
  823. * 为dialog中的button设置icon,参数结构
  824. * [{
  825. * text: '暂存',
  826. * title: '暂时存储',
  827. * icons: {
  828. * primary: 'ui-icon-disk'
  829. * }
  830. * }]
  831. * @param {Object} options
  832. */
  833. setAttrs: function(options) {
  834. var _set_btns = [];
  835. $.each(options, function(i, v) {
  836. _set_btns[_set_btns.length] = v;
  837. });
  838. $.each(_set_btns, function(i, v) {
  839. var $btn = $('.ui-button-text').filter(function() {
  840. return $(this).text() == v.text;
  841. }).parent();
  842. var _icons = {};
  843. if (v.icons) {
  844. var arrayIcons = v.icons.split(' ');
  845. if (arrayIcons.length == 1) {
  846. _icons.primary = arrayIcons[0];
  847. } else if (arrayIcons.length == 2) {
  848. _icons.primary = arrayIcons[0];
  849. _icons.secondary = arrayIcons[1];
  850. }
  851. $btn.button({
  852. icons: _icons
  853. });
  854. }
  855. $btn.attr('title', v.title);
  856. // 分隔符
  857. try {
  858. if (v.division) {
  859. var position = v.division || 'after';
  860. if (position == 'before') {
  861. $btn.before("<span class='ui-state-error ui-dialog-button-devision'></span>");
  862. } else if (position == 'after') {
  863. $btn.after("<span class='ui-state-error ui-dialog-button-devision'></span>");
  864. } else {
  865. alert('未知位置:' + position);
  866. }
  867. }
  868. } catch (e) {
  869. }
  870. });
  871. },
  872. /*[{
  873. text: 'aaa',
  874. position: ['left'|'right']
  875. }]*/
  876. group: function(opts) {
  877. $.each(opts, function(i, v) {
  878. var $btn = $('.ui-button-text').filter(function() {
  879. return $(this).text() == v.text;
  880. }).parent();
  881. try {
  882. if (!v.position || v.position == 'after') {
  883. $btn.after("<span class='ui-state-error ui-dialog-button-devision'></span>");
  884. } else if (v.position == 'before') {
  885. $btn.before("<span class='ui-state-error ui-dialog-button-devision'></span>");
  886. } else {
  887. alert('请设置position|by dialog.button.group');
  888. }
  889. } catch (e) {
  890. }
  891. });
  892. }
  893. },
  894. /**
  895. * 根据浏览器差异获取window的高度
  896. */
  897. getBodyHeight: function() {
  898. var tempBodyHeight = document.documentElement.clientHeight;
  899. if ($.common.browser.isIE()) {
  900. //tempBodyHeight += 150;
  901. } else {
  902. tempBodyHeight -= 10;
  903. }
  904. return tempBodyHeight;
  905. },
  906. /**
  907. * 根据浏览器差异获取设置对话框的高度
  908. */
  909. getHeight: function(_height) {
  910. var tempBodyHeight = _height;
  911. if ($.common.browser.isIE()) {
  912. tempBodyHeight += 100;
  913. } else {
  914. tempBodyHeight -= 10;
  915. }
  916. return tempBodyHeight;
  917. }
  918. },
  919. /**
  920. * 选项卡相关
  921. */
  922. tab: {
  923. /**
  924. * 自动设置选项卡的高度
  925. * @param {Object} options
  926. */
  927. autoHeight: function(options) {
  928. var defaults = {
  929. increment: {
  930. ie: 0,
  931. firefox: 0,
  932. chrome: 0
  933. }
  934. };
  935. options = $.extend({}, defaults, options);
  936. /**
  937. * 核心处理函数
  938. */
  939. function innerDeal() {
  940. // 非IE默认值
  941. var gap = 80;
  942. // 特殊处理IE
  943. if ($.common.browser.isIE()) {
  944. gap = 60;
  945. gap += options.increment.ie;
  946. } else if ($.common.browser.isMozila()) {
  947. gap += options.increment.firefox;
  948. } else if ($.common.browser.isChrome()) {
  949. gap += options.increment.chrome;
  950. }
  951. var height = document.body.clientHeight - gap;
  952. $('.ui-tabs-panel').height(height);
  953. if ($.isFunction(options.callback)) {
  954. options.callback();
  955. }
  956. }
  957. innerDeal();
  958. // 窗口大小改变的时候
  959. window.onresize = innerDeal;
  960. }
  961. },
  962. /**
  963. * 一些特效
  964. */
  965. effect: {
  966. /*
  967. * 斑马效果
  968. */
  969. zebra: function(selector) {
  970. $(selector).hover(function() {
  971. $(this).addClass('ui-state-hover');
  972. }, function() {
  973. $(this).removeClass('ui-state-hover');
  974. });
  975. }
  976. },
  977. /**
  978. * 自动完成
  979. */
  980. autocomplete: {
  981. /*
  982. * 触发自动完成
  983. */
  984. triggerSearch: function(e) {
  985. if ($(this).val().length > 0) {
  986. $(this).autocomplete('search', $(this).val());
  987. }
  988. },
  989. /*
  990. * 取消自动完成的结果,配合triggerSearch使用,目的是针对文本框获取焦点之后就自动根据现有内容搜索后点击死循环问题
  991. */
  992. cancelResult: function(ele) {
  993. setTimeout(function() {
  994. $('.ui-autocomplete').hide();
  995. }, 50);
  996. }
  997. }
  998. };
  999. /*******************************************/
  1000. /** jQuery UI--结束 **/
  1001. /*******************************************/
  1002. /*******************************************/
  1003. /** jstree --开始 **/
  1004. /*******************************************/
  1005. var _plugin_jstree = {
  1006. // 单击名称展开子节点
  1007. clickNameToUnfold: function(jstreeObj) {
  1008. $(jstreeObj).bind('click.jstree', function(event) {
  1009. var eventNodeName = event.target.nodeName;
  1010. if (eventNodeName == 'INS') {
  1011. return;
  1012. } else if (eventNodeName == 'A') {
  1013. var $city = $(event.target);
  1014. // 点击A展开子节点
  1015. $("#areaInfoTree").jstree('toggle_node', $city.parent().find('ins').get(0));
  1016. if ($city.attr('leaf')) {
  1017. $('#result').text($city.text() + ",ID=" + $city.parent().attr('id'));
  1018. }
  1019. }
  1020. });
  1021. }
  1022. };
  1023. /*******************************************/
  1024. /** jstree --结束 **/
  1025. /*******************************************/
  1026. /*******************************************/
  1027. /** workflow --开始 **/
  1028. /*******************************************/
  1029. var _plugin_workflow = {
  1030. setButtonIcons: function() {
  1031. _plugin_jqui.dialog.button.setIcons({
  1032. 提交: {
  1033. primary: 'ui-icon-arrowthick-1-e'
  1034. },
  1035. 退回: {
  1036. primary: 'ui-icon-arrowreturnthick-1-w'
  1037. },
  1038. 流程跟踪: {
  1039. primary: 'ui-icon-flag'
  1040. },
  1041. 启动: {
  1042. primary: 'ui-icon-play'
  1043. },
  1044. 签收: {
  1045. primary: 'ui-icon-check'
  1046. },
  1047. 保存: {
  1048. primary: 'ui-icon-disk'
  1049. },
  1050. 关闭: {
  1051. primary: 'ui-icon-cancel'
  1052. },
  1053. 同意: {
  1054. primary: 'ui-icon-check'
  1055. },
  1056. 不同意: {
  1057. primary: 'ui-icon-closethick'
  1058. },
  1059. 通知付费: {
  1060. primary: 'ui-icon-mail-closed'
  1061. }
  1062. });
  1063. }
  1064. };
  1065. /*******************************************/
  1066. /** workflow --开始 **/
  1067. /*******************************************/
  1068. /*******************************************/
  1069. /** $.common--开始 **/
  1070. /*******************************************/
  1071. var _common_plugins = {
  1072. // jqGrid默认参数
  1073. jqGrid: _plugin_jqGrid,
  1074. validator: _plugin_validator,
  1075. jqui: _plugin_jqui,
  1076. jstree: _plugin_jstree,
  1077. workflow: _plugin_workflow
  1078. };
  1079. // 插件扩展
  1080. $.common.plugin = _common_plugins;
  1081. //-- frame工具 --//
  1082. $.common.frame = {
  1083. /**
  1084. * 让iframe自适应高度
  1085. */
  1086. autoSizeIframe: function(iframeId) {
  1087. var parentHeight = $('#' + iframeId).parent();
  1088. $('#' + iframeId).height(parentHeight);
  1089. }
  1090. };
  1091. //-- 和系统有关的函数 --//
  1092. $.common.system = {
  1093. // 获取系统属性
  1094. getProp: function(options) {
  1095. var defaults = {
  1096. url: ctx + '/common/sysprop!findProp.action',
  1097. params: {
  1098. key: ''
  1099. },
  1100. callback: null,
  1101. error: null
  1102. };
  1103. $.extend(true, defaults, options);
  1104. $.ajax({
  1105. url: defaults.url,
  1106. cache: false,
  1107. dataType: 'json',
  1108. data: defaults.params,
  1109. success: function(prop, textStatus) {
  1110. if ($.isFunction(defaults.callback)) {
  1111. defaults.callback(prop);
  1112. }
  1113. },
  1114. error: function(XMLHttpRequest, textStatus, errorThrown) {
  1115. if ($.isFunction(defaults.error)) {
  1116. defaults.error(XMLHttpRequest, textStatus, errorThrown);
  1117. }
  1118. }
  1119. });
  1120. },
  1121. /*
  1122. * 为下拉框加载数据字典
  1123. */
  1124. loadDicts: function() {
  1125. var dictUrl = _sub_sys_url.common + '/common/system-dictionary!findTypeForOption.action'
  1126. $('.dict-code').each(function() {
  1127. var srcEle = this;
  1128. $.post(dictUrl, {
  1129. type: $(srcEle).attr('dicttype')
  1130. }, function(resp) {
  1131. $(srcEle).html(resp);
  1132. });
  1133. });
  1134. }
  1135. };
  1136. //-- 浏览器工具 --//
  1137. $.common.browser = {
  1138. // 检测是否是IE浏览器
  1139. isIE: function() {
  1140. var _uaMatch = $.uaMatch(navigator.userAgent);
  1141. var _browser = _uaMatch.browser;
  1142. if (_browser == 'msie') {
  1143. return true;
  1144. } else {
  1145. return false;
  1146. }
  1147. },
  1148. // 检测是否是chrome浏览器
  1149. isChrome: function() {
  1150. var _uaMatch = $.uaMatch(navigator.userAgent);
  1151. var _browser = _uaMatch.browser;
  1152. if (_browser == 'webkit') {
  1153. return true;
  1154. } else {
  1155. return false;
  1156. }
  1157. },
  1158. // 检测是否是Firefox浏览器
  1159. isMozila: function() {
  1160. var _uaMatch = $.uaMatch(navigator.userAgent);
  1161. var _browser = _uaMatch.browser;
  1162. if (_browser == 'mozilla') {
  1163. return true;
  1164. } else {
  1165. return false;
  1166. }
  1167. },
  1168. // 检测是否是Firefox浏览器
  1169. isOpera: function() {
  1170. var _uaMatch = $.uaMatch(navigator.userAgent);
  1171. var _browser = _uaMatch.browser;
  1172. if (_browser == 'opera') {
  1173. return true;
  1174. } else {
  1175. return false;
  1176. }
  1177. }
  1178. };
  1179. //-- 编码相关 --//
  1180. $.common.code = {
  1181. /**
  1182. * 把文本转换为HTML代码
  1183. * @param {Object} text 原始文本
  1184. */
  1185. htmlEncode: function(text) {
  1186. var textold;
  1187. do {
  1188. textold = text;
  1189. text = text.replace("\n", "<br>");
  1190. text = text.replace("\n", "<br/>");
  1191. text = text.replace("\n", "<BR/>");
  1192. text = text.replace("\n", "<BR>");
  1193. text = text.replace(" ", "&nbsp;");
  1194. } while (textold != text);
  1195. return text;
  1196. },
  1197. /**
  1198. * 把HTML代码转换为文本
  1199. * @param {Object} text 原始HTML代码
  1200. */
  1201. htmlDecode: function(text) {
  1202. var textold;
  1203. do {
  1204. textold = text;
  1205. text = text.replace("<br>", "\n");
  1206. text = text.replace("<br/>", "\n");
  1207. text = text.replace("<BR>", "\n");
  1208. text = text.replace("<BR/>", "\n");
  1209. text = text.replace("&nbsp;", " ");
  1210. } while (textold != text);
  1211. return text;
  1212. }
  1213. };
  1214. //-- 数学工具 --//
  1215. $.common.math = {
  1216. /*
  1217. * 四舍五入
  1218. */
  1219. round: function(dight, how) {
  1220. return dight.toFixed(how);
  1221. }
  1222. };
  1223. //-- 文件相关 --//
  1224. $.common.file = {
  1225. /**
  1226. * 下载文件
  1227. * @fileName 相对于Web根路径
  1228. */
  1229. download: function(fileName) {
  1230. var downUrl = ctx + '/file/download.action?fileName=' + fileName;
  1231. location.href = encodeURI(encodeURI(downUrl));
  1232. },
  1233. /**
  1234. * 友好文件大小:KB、MB
  1235. */
  1236. friendlySize: function(size) {
  1237. if (size < 1024 * 1024) {
  1238. return $.common.math.round(size / 1024, 2) + "KB";
  1239. } else {
  1240. return $.common.math.round(size / (1024 * 1024), 2) + "MB";
  1241. }
  1242. }
  1243. };
  1244. //-- 字符工具 --//
  1245. $.common.string = {
  1246. /*
  1247. * 如果对象为空返回空字符串
  1248. */
  1249. emptyIfNull: function(str) {
  1250. return str ? str : '';
  1251. }
  1252. };
  1253. //-- 未分类 --//
  1254. $.common.custom = {
  1255. // 得到应用名
  1256. getCtx: function() {
  1257. try {
  1258. return ctx || '';
  1259. } catch (e) {
  1260. //alert('没有设置ctx变量');
  1261. }
  1262. },
  1263. getLoadingImg: function() {
  1264. return '<img src="' + $.common.custom.getCtx() + '/images/ajax/loading.gif" align="absmiddle"/>&nbsp;';
  1265. },
  1266. /**
  1267. * 创建小时下拉框
  1268. */
  1269. createHourSelect: function(selectId, defaultValue) {
  1270. var hours = new StringBuffer();
  1271. var tempValue = "";
  1272. for (var i = 0; i < 24; i++) {
  1273. if (i < 10) {
  1274. tempValue = "0" + i;
  1275. } else {
  1276. tempValue = i;
  1277. }
  1278. hours.append("<option value='" + tempValue + "'" + (defaultValue == tempValue ? " selected" : "") + ">" + tempValue + "</option>");
  1279. }
  1280. $(selectId).append(hours.toString());
  1281. },
  1282. /**
  1283. * 创建分钟下拉框
  1284. */
  1285. createMinuteSelect: function(selectId, defaultValue) {
  1286. var hours = new StringBuffer();
  1287. var tempValue = "";
  1288. for (var i = 0; i < 60; i++) {
  1289. if (i < 10) {
  1290. tempValue = "0" + i;
  1291. } else {
  1292. tempValue = i;
  1293. }
  1294. hours.append("<option value='" + tempValue + "'" + (defaultValue == tempValue ? " selected" : "") + ">" + tempValue + "</option>");
  1295. }
  1296. $(selectId).append(hours.toString());
  1297. },
  1298. /**
  1299. * 日期增加年数或月数或天数
  1300. * @param {String} BaseDate 要增加的日期
  1301. * @param {Object} interval 增加数量
  1302. * @param {Object} DatePart 增加哪一部分
  1303. * @param {String} ReturnType 返回类型strunt|date
  1304. */
  1305. dateAdd: function(BaseDate, interval, DatePart, ReturnType) {
  1306. var dateObj;
  1307. if (typeof BaseDate == 'object') {
  1308. dateObj = BaseDate;
  1309. } else {
  1310. var strDs = BaseDate.split('-');
  1311. var year = parseInt(strDs[0]);
  1312. var month = parseInt(strDs[1]);
  1313. var date = parseInt(strDs[2]);
  1314. dateObj = new Date(year, month, date);
  1315. }
  1316. ReturnType = ReturnType || 'string';
  1317. var millisecond = 1;
  1318. var second = millisecond * 1000;
  1319. var minute = second * 60;
  1320. var hour = minute * 60;
  1321. var day = hour * 24;
  1322. var year = day * 365;
  1323. var newDate;
  1324. var dVal = new Date(dateObj);
  1325. var dVal = dVal.valueOf();
  1326. switch (DatePart) {
  1327. case "ms":
  1328. newDate = new Date(dVal + millisecond * interval);
  1329. break;
  1330. case "s":
  1331. newDate = new Date(dVal + second * interval);
  1332. break;
  1333. case "mi":
  1334. newDate = new Date(dVal + minute * interval);
  1335. break;
  1336. case "h":
  1337. newDate = new Date(dVal + hour * interval);
  1338. break;
  1339. case "d":
  1340. newDate = new Date(dVal + day * interval);
  1341. break;
  1342. case "y":
  1343. newDate = new Date(dVal + year * interval);
  1344. break;
  1345. default:
  1346. return escape("日期格式不对");
  1347. }
  1348. newDate = new Date(newDate);
  1349. if (ReturnType == 'string') {
  1350. return newDate.getFullYear() + "-" + newDate.getMonth() + "-" + newDate.getDate();
  1351. } else if (ReturnType == 'date') {
  1352. return newDate;
  1353. }
  1354. },
  1355. /**
  1356. * 把毫秒转换为自然语言
  1357. * @param {Object} millis
  1358. */
  1359. timeRange: function(millis) {
  1360. // 计算出相差天数
  1361. var days = Math.floor(millis / (24 * 3600 * 1000));
  1362. // 计算相差小时
  1363. var leave1 = millis % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  1364. var hours = Math.floor(leave1 / (3600 * 1000));
  1365. //计算相差分钟数
  1366. var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  1367. var minutes = Math.floor(leave2 / (60 * 1000));
  1368. //计算相差秒数
  1369. var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  1370. var seconds = Math.round(leave3 / 1000);
  1371. var result = "";
  1372. if (days > 0) {
  1373. result += days + "天";
  1374. }
  1375. if (hours > 0) {
  1376. result = result == "" ? "" : result + " ";
  1377. result += hours + "小时";
  1378. }
  1379. if (minutes > 0) {
  1380. result = result == "" ? "" : result + " ";
  1381. result += minutes + "分钟";
  1382. }
  1383. if (seconds > 0) {
  1384. result = result == "" ? "" : result + " ";
  1385. result += seconds + "秒";
  1386. }
  1387. return result;
  1388. //return "相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒";
  1389. }
  1390. };
  1391. /*******************************************/
  1392. /** $.form--开始 **/
  1393. /*******************************************/
  1394. //-- 表单自定义功能 --//
  1395. $.form = {};
  1396. // 绑定form的ajax提交功能
  1397. $.form.bindAjaxSubmit = function(settings) {
  1398. var defaults = {
  1399. formId: '',
  1400. beforeSubmit: showRequest,
  1401. success: showResponse,
  1402. clearForm: true
  1403. };
  1404. settings = $.extend({}, defaults, settings);
  1405. // 重要:防止重复绑定
  1406. if ($(settings.formId).data('binded') === true) {
  1407. return;
  1408. };
  1409. $(settings.formId).data('binded', true).submit(function(e) {
  1410. $(this).ajaxSubmit(settings);
  1411. return false;
  1412. });
  1413. };
  1414. // 表示层设置
  1415. $.form.ui = {
  1416. // 红色星号
  1417. required: function() {
  1418. return $.common.plugin.jqGrid.form.must();
  1419. },
  1420. // 根据属性设置
  1421. initRequired: function(selector) {
  1422. $('.required', selector).each(function() {
  1423. if ($(this).parent().find('.must').length >= 1) {
  1424. $(this).parent().find('.must').remove();
  1425. }
  1426. $(this).after($.common.plugin.jqGrid.form.must());
  1427. });
  1428. }
  1429. };
  1430. // -- 自定义插件 --//
  1431. /**
  1432. * 插件名称:cursorInsert(光标处插入) 功能:可以在文本框的
  1433. */
  1434. $.fn.cursorInsert = function(options) {
  1435. // default settings
  1436. var settings = {
  1437. content: ''
  1438. };
  1439. if (options) {
  1440. $.extend(settings, options);
  1441. }
  1442. return this.each(function() {
  1443. var obj = $(this).get(0);
  1444. if (document.selection) {
  1445. obj.focus();
  1446. var sel = document.selection.createRange();
  1447. document.selection.empty();
  1448. sel.text = options.content;
  1449. } else {
  1450. var prefix, main, suffix;
  1451. prefix = obj.value.substring(0, obj.selectionStart);
  1452. main = obj.value.substring(obj.selectionStart, obj.selectionEnd);
  1453. suffix = obj.value.substring(obj.selectionEnd);
  1454. obj.value = prefix + options.content + suffix;
  1455. }
  1456. obj.focus();
  1457. });
  1458. };
  1459. /**
  1460. * 随滚动条滚动
  1461. */
  1462. $.fn.autoScroll = function() {
  1463. var _this = this;
  1464. $(_this).css({
  1465. position: 'absolute'
  1466. });
  1467. $(window).scroll(function() {
  1468. $(_this).css({
  1469. top: $(this).scrollTop() + $(this).height() - 500
  1470. });
  1471. });
  1472. };
  1473. /**
  1474. * 动态加载JavaScript
  1475. */
  1476. $.loadScript = function(options) {
  1477. var ga = document.createElement('script');
  1478. ga.type = 'text/javascript';
  1479. ga.async = true;
  1480. ga.src = options.src;
  1481. var s = document.getElementsByTagName('script')[0];
  1482. s.parentNode.insertBefore(ga, s);
  1483. };
  1484. /*
  1485. * 是否可以写日志
  1486. */
  1487. function can_log() {
  1488. if (javascript_log_enable == false || $.common.browser.isIE()) {
  1489. return false;
  1490. }
  1491. return console != undefined;
  1492. };
  1493. /**
  1494. * jquery插件形式的firebug日志
  1495. * @param {Object} msg
  1496. */
  1497. $.fn.log = function(msg) {
  1498. if (!can_log()) {
  1499. return this;
  1500. }
  1501. console.log("%s: %o", msg, this);
  1502. return this;
  1503. };
  1504. $.log = $.log || {};
  1505. /**
  1506. * firebug日志
  1507. * @param {Object} msg
  1508. */
  1509. $.extend($.log, {
  1510. log: function(msg) {
  1511. if (!can_log()) {
  1512. return;
  1513. }
  1514. console.log(msg);
  1515. },
  1516. debug: function(msg) {
  1517. if (!can_log()) {
  1518. return;
  1519. }
  1520. console.debug(msg);
  1521. },
  1522. info: function(msg) {
  1523. if (!can_log()) {
  1524. return;
  1525. }
  1526. console.info(msg);
  1527. },
  1528. warn: function(msg) {
  1529. if (!can_log()) {
  1530. return;
  1531. }
  1532. console.warn(msg);
  1533. },
  1534. error: function(msg) {
  1535. if (!can_log()) {
  1536. return;
  1537. }
  1538. console.error(msg);
  1539. }
  1540. });
  1541. /**
  1542. * 获取元素的outerHTML
  1543. */
  1544. $.fn.outerHTML = function() {
  1545. // IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
  1546. return (!this.length) ? this : (this[0].outerHTML ||
  1547. (function(el) {
  1548. var div = document.createElement('div');
  1549. div.appendChild(el.cloneNode(true));
  1550. var contents = div.innerHTML;
  1551. div = null;
  1552. return contents;
  1553. })(this[0]));
  1554. };
  1555. })(jQuery);
  1556. //-- 自定义函数 --//
  1557. function _initFunction() {
  1558. $.extend({
  1559. jsonToString: function(object) {
  1560. if (object == null) {
  1561. return 'null';
  1562. }
  1563. var type = typeof object;
  1564. if ('object' == type) {
  1565. if (Array == object.constructor) {
  1566. type = 'array';
  1567. } else if (RegExp == object.constructor) {
  1568. type = 'regexp';
  1569. } else {
  1570. type = 'object';
  1571. }
  1572. }
  1573. switch (type) {
  1574. case 'undefined':
  1575. case 'unknown':{
  1576. return;
  1577. break;
  1578. }
  1579. case 'function':{
  1580. return '"' + object() + '"';
  1581. break;
  1582. }
  1583. case 'boolean':
  1584. case 'regexp':{
  1585. return object.toString();
  1586. break;
  1587. }
  1588. case 'number':{
  1589. return isFinite(object) ? object.toString() : 'null';
  1590. break;
  1591. }
  1592. case 'string':{
  1593. return '"' +
  1594. object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function() {
  1595. var a = arguments[0];
  1596. return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : ""
  1597. }) +
  1598. '"';
  1599. break;
  1600. }
  1601. case 'object':{
  1602. if (object === null)
  1603. return 'null';
  1604. var results = [];
  1605. for (var property in object) {
  1606. var value = jquery.jsonToString(object[property]);
  1607. if (value !== undefined)
  1608. results.push(jquery.jsonToString(property) + ':' + value);
  1609. }
  1610. return '{' + results.join(',') + '}';
  1611. break;
  1612. }
  1613. case 'array':{
  1614. var results = [];
  1615. for (var i = 0; i < object.length; i++) {
  1616. var value = jquery.jsonToString(object[i]);
  1617. if (value !== undefined)
  1618. results.push(value);
  1619. }
  1620. return '[' + results.join(',') + ']';
  1621. break;
  1622. }
  1623. }
  1624. }
  1625. });
  1626. // 全局ajax设置
  1627. $.ajaxSetup({
  1628. cache: false,
  1629. global: true,
  1630. jsonp: null,
  1631. jsonpCallback: null,
  1632. complete: function(req, status) {
  1633. if (!req.responseText) {
  1634. return;
  1635. }
  1636. if (req.responseText == '_login_timeout' || req.responseText.indexOf('登录页') != -1) {
  1637. // 打开重新登录窗口
  1638. if ($.isFunction($.common.window.getTopWin().relogin)) {
  1639. $.common.window.getTopWin().relogin();
  1640. } else {
  1641. alert('登录已超时,请保存数据后重新登录!');
  1642. }
  1643. }
  1644. },
  1645. error: function(req, status) {
  1646. var reqText = req.responseText;
  1647. if (reqText == 'login') {
  1648. return;
  1649. }
  1650. if (reqText == 'error') {
  1651. alert('提示:操作失败!');
  1652. } else if (reqText != '') {
  1653. alert("提示:" + reqText);
  1654. }
  1655. }
  1656. });
  1657. // jqgrid
  1658. if ($.jgrid) {
  1659. $.jgrid.no_legacy_api = true;
  1660. $.jgrid.useJSON = true;
  1661. $.jgrid.ajaxOptions.type = 'post';
  1662. }
  1663. // blockui support linux FF
  1664. if ($.blockUI) {
  1665. var userAgent = $.uaMatch(navigator.userAgent);
  1666. if (userAgent.browser == 'mozilla' && navigator.userAgent.indexOf('Linux') != -1) {
  1667. // enable transparent overlay on FF/Linux
  1668. $.blockUI.defaults.applyPlatformOpacityRules = false;
  1669. }
  1670. }
  1671. // jquery validator
  1672. if ($.validator) {
  1673. // 银行卡号
  1674. $.validator.addMethod("bankcard", function(value, element, params) {
  1675. var regPex = /(^\d{16}|^\d{17}|^\d{18}|^\d{19}|^\d{20})$/;
  1676. return this.optional(element) || regPex.exec(value);
  1677. }, jQuery.format("请输入合法的银行卡号(长度:16~20)"));
  1678. // 不能大于当天
  1679. $.validator.addMethod("canNotMoreThanToday", function(value, element, params) {
  1680. var values = value.split('-');
  1681. return this.optional(element) || new Date(values[0], values[1], values[2]).getMilliseconds() <= new Date().getMilliseconds();
  1682. }, jQuery.format("日期不能大于今天!"));
  1683. }
  1684. };
  1685. //-- Javascript对象扩展--开始-//
  1686. /**
  1687. * 去掉开头、结尾的空格
  1688. *
  1689. * @return {}
  1690. */
  1691. String.prototype.trim = function() {
  1692. return this.replace(/(^\s+)|\s+$/g, "");
  1693. };
  1694. /**
  1695. * 转换字符串为json对象
  1696. */
  1697. String.prototype.toJson = function() {
  1698. return eval('(' + this + ')');
  1699. };
  1700. String.prototype.endsWithIgnoreCase = function(str) {
  1701. return (this.toUpperCase().match(str.toUpperCase() + "$") == str.toUpperCase()) ||
  1702. (this.toLowerCase().match(str.toLowerCase() + "$") == str.toLowerCase());
  1703. }
  1704. /**
  1705. * 输出2010-02-05格式的日期字符串
  1706. *
  1707. * @return {}
  1708. */
  1709. Date.prototype.toDateStr = function() {
  1710. return ($.common.browser.isMozila() || $.common.browser.isChrome() ? (this.getYear() + 1900) : this.getYear()) + "-" +
  1711. (this.getMonth() < 10 ? "0" + this.getMonth() : this.getMonth()) +
  1712. "-" +
  1713. (this.getDate() < 10 ? "0" + this.getDate() : this.getDate());
  1714. };
  1715. /**
  1716. * 日期格式化
  1717. * @param {Object} format
  1718. */
  1719. Date.prototype.format = function(format) {
  1720. var o = {
  1721. "M+": this.getMonth() + 1, //month
  1722. "d+": this.getDate(), //day
  1723. "h+": this.getHours(), //hour
  1724. "m+": this.getMinutes(), //minute
  1725. "s+": this.getSeconds(), //second
  1726. "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
  1727. "S": this.getMilliseconds() //millisecond
  1728. }
  1729. if (/(y+)/.test(format))
  1730. format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  1731. for (var k in o)
  1732. if (new RegExp("(" + k + ")").test(format))
  1733. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  1734. return format;
  1735. }
  1736. /**
  1737. * 将字符串格式的日期转换为日期类型对象
  1738. * @param {Object} strDate
  1739. */
  1740. Date.toDate = function(strDate) {
  1741. var strDs = strDate.split('-');
  1742. var year = parseInt(strDs[0]);
  1743. var month = parseInt(strDs[1]);
  1744. var date = parseInt(strDs[2]);
  1745. return new Date(year, month, date);
  1746. };
  1747. /**
  1748. * 通过当前时间计算当前周数
  1749. */
  1750. Date.prototype.getWeekNumber = function() {
  1751. var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
  1752. var DoW = d.getDay();
  1753. d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
  1754. var ms = d.valueOf(); // GMT
  1755. d.setMonth(0);
  1756. d.setDate(4); // Thu in Week 1
  1757. return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
  1758. }
  1759. //+---------------------------------------------------
  1760. //| 日期计算
  1761. //+---------------------------------------------------
  1762. Date.prototype.DateAdd = function(strInterval, Number) {
  1763. var dtTmp = this;
  1764. switch (strInterval) {
  1765. case 's':
  1766. return new Date(Date.parse(dtTmp) + (1000 * Number));
  1767. case 'n':
  1768. return new Date(Date.parse(dtTmp) + (60000 * Number));
  1769. case 'h':
  1770. return new Date(Date.parse(dtTmp) + (3600000 * Number));
  1771. case 'd':
  1772. return new Date(Date.parse(dtTmp) + (86400000 * Number));
  1773. case 'w':
  1774. return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
  1775. case 'q':
  1776. return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
  1777. case 'm':
  1778. return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
  1779. case 'y':
  1780. return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
  1781. }
  1782. };
  1783. //-- Javascript对象扩展--结束 -//
  1784. //-- 自定义类-开始 --/
  1785. function StringBuffer() {
  1786. this._strings_ = new Array();
  1787. }
  1788. StringBuffer.prototype.append = function(str) {
  1789. this._strings_.push(str);
  1790. return this;
  1791. };
  1792. StringBuffer.prototype.toString = function() {
  1793. return this._strings_.join("").trim();
  1794. };
  1795. /**
  1796. * 以键值对存储
  1797. */
  1798. function Map() {
  1799. var struct = function(key, value) {
  1800. this.key = key;
  1801. this.value = value;
  1802. };
  1803. var put = function(key, value) {
  1804. for (var i = 0; i < this.arr.length; i++) {
  1805. if (this.arr[i].key === key) {
  1806. this.arr[i].value = value;
  1807. return;
  1808. }
  1809. }
  1810. this.arr[this.arr.length] = new struct(key, value);
  1811. this._keys[this._keys.length] = key;
  1812. };
  1813. var get = function(key) {
  1814. for (var i = 0; i < this.arr.length; i++) {
  1815. if (this.arr[i].key === key) {
  1816. return this.arr[i].value;
  1817. }
  1818. }
  1819. return null;
  1820. };
  1821. var remove = function(key) {
  1822. var v;
  1823. for (var i = 0; i < this.arr.length; i++) {
  1824. v = this.arr.pop();
  1825. if (v.key === key) {
  1826. continue;
  1827. }
  1828. this.arr.unshift(v);
  1829. this._keys.unshift(v);
  1830. }
  1831. };
  1832. var size = function() {
  1833. return this.arr.length;
  1834. };
  1835. var keys = function() {
  1836. return this._keys;
  1837. };
  1838. var isEmpty = function() {
  1839. return this.arr.length <= 0;
  1840. };
  1841. this.arr = new Array();
  1842. this._keys = new Array();
  1843. this.keys = keys;
  1844. this.get = get;
  1845. this.put = put;
  1846. this.remove = remove;
  1847. this.size = size;
  1848. this.isEmpty = isEmpty;
  1849. }
  1850. /**
  1851. * 更新jquery ui css
  1852. * @param {Object} locStr
  1853. */
  1854. function updateCSS(locStr) {
  1855. var cssLink = $('<link href="' + locStr + '" type="text/css" rel="Stylesheet" class="ui-theme" />');
  1856. $("head").append(cssLink);
  1857. if ($("link.ui-theme").size() > 3) {
  1858. $("link.ui-theme:first").remove();
  1859. }
  1860. }
  1861. /**
  1862. * 更新自定义CSS
  1863. */
  1864. function updateCustomCss() {
  1865. var customStyleUrl = ctx + '/css/style.css';
  1866. var cssLink = $('<link href="' + customStyleUrl + '" type="text/css" rel="Stylesheet" class="custom-style" />');
  1867. $("head").append(cssLink);
  1868. if ($("link.custom-style").size() > 3) {
  1869. $("link.custom-style:first").remove();
  1870. }
  1871. }
  1872. /**
  1873. * 引入css、script文件
  1874. * @param {Object} file
  1875. */
  1876. function include(file) {
  1877. var files = typeof file == "string" ? [file] : file;
  1878. for (var i = 0; i < files.length; i++) {
  1879. var name = files[i].replace(/^\s|\s$/g, "");
  1880. var att = name.split('.');
  1881. var ext = att[att.length - 1].toLowerCase();
  1882. var isCSS = ext == "css";
  1883. var tag = isCSS ? "link" : "script";
  1884. var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
  1885. var link = (isCSS ? "href" : "src") + "='" + '' + name + "'";
  1886. if ($(tag + "[" + link + "]").length == 0) {
  1887. $("<" + tag + attr + link + "></" + tag + ">").appendTo('head');
  1888. }
  1889. }
  1890. }
  1891. //-- 自定义类-结束 --/