企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
static\plugins\siyu-ui.js ``` /** * 通用js方法封装处理 * Copyright (c) 2019 siyucms */ (function ($) { $.extend({ btTable: {}, // bootstrapTable // 表格封装处理 table: { _option: {}, // 初始化表格参数 init: function(options) { // 默认参数 var defaults = { id: "bootstrap-table", height: undefined, // 表格的高度,一般不需要设置 sidePagination: "server", // server启用服务端分页client客户端分页 sortName: "id", // 排序列名称 sortOrder: "desc", // 排序方式 asc 或者 desc escape: true, // 转义HTML字符串 pagination: true, // 是否显示分页 pageSize: 10, // 每页的记录行数 showRefresh: true, // 是否显示刷新按钮 showToggle: true, // 是否显示详细视图和列表视图的切换按钮 showFullscreen: true, // 是否显示全屏按钮 showColumns: true, // 是否显示隐藏某列下拉框 search: false, // 是否显示自带的搜索框功能 showSearchButton: false, // 是否显示自带的搜索按钮 pageList: [10, 25, 50, 100], // 每页显示的数量选择 toolbar: "toolbar", // 自定义工具栏 toolbarAlign: "left", // 工具栏左对齐 buttonsClass: "", // 按钮样式 showFooter: false, // 显示页脚 showExport: false, // 显示导出按钮 clickToSelect: false, // 是否启用点击选中行 fixedColumns: false, // 是否启用固定列功能 rowStyle: {}, // 设置行样式 classes: 'table table-hover', // 设置表样式 queryParams: $.table.queryParams, }; var options = $.extend(defaults, options); $.table._option = options; $.btTable = $('#' + options.id); // 初始化新事件对象的属性 $.table.initEvent(); // 构建bootstrap数据 var option = { url: options.url, // 请求后台的URL(*) height: options.height, // 表格的高度 sortable: true, // 是否启用排序 sortName: options.sortName, // 排序列名称 sortOrder: options.sortOrder, // 排序方式 asc 或者 desc sortStable: true, // 设置为 true 将获得稳定的排序 method: 'post', // 请求方式(*) cache: false, // 是否使用缓存 contentType: "application/json", // 内容类型 dataType: 'json', // 数据类型 responseHandler: $.table.responseHandler, // 在加载服务器发送来的数据之前处理函数 pagination: options.pagination, // 是否显示分页(*) paginationLoop: true, // 是否禁用分页连续循环模式 sidePagination: options.sidePagination, // server启用服务端分页client客户端分页 pageNumber: 1, // 初始化加载第一页,默认第一页 pageSize: options.pageSize, // 每页的记录行数(*) pageList: options.pageList, // 可供选择的每页的行数(*) search: options.search, // 是否显示搜索框功能 showSearchButton: options.showSearchButton, // 是否显示检索信息 showColumns: options.showColumns, // 是否显示隐藏某列下拉框 showRefresh: options.showRefresh, // 是否显示刷新按钮 showToggle: options.showToggle, // 是否显示详细视图和列表视图的切换按钮 showFullscreen: options.showFullscreen, // 是否显示全屏按钮 showFooter: options.showFooter, // 是否显示页脚 escape: options.escape, // 转义HTML字符串 clickToSelect: options.clickToSelect, // 是否启用点击选中行 toolbar: '#' + options.toolbar, // 指定工作栏 detailView: options.detailView, // 是否启用显示细节视图 iconSize: 'undefined', // 图标大小:undefined默认的按钮尺寸 xs超小按钮sm小按钮lg大按钮 rowStyle: options.rowStyle, // 通过自定义函数设置行样式 showExport: options.showExport, // 是否支持导出文件 uniqueId: options.uniqueId, // 唯 一的标识符 fixedColumns: options.fixedColumns, // 是否启用冻结列(左侧) detailFormatter: options.detailFormatter, // 在行下面展示其他数据列表 columns: options.columns, // 显示列信息(*) classes: options.classes, // 设置表样式 queryParams: options.queryParams, // 传递参数(*) onDblClickRow: function (row, $element, field) { // 双击一行时触发编辑动作 var edit = $element.children("td").last().html(); if ($.common.isNotEmpty(edit) && edit.indexOf('$.operate.edit') != -1) { $.operate.edit($element.data('uniqueid')); } } }; // 将tree合并到option[关闭分页且传递父id字段才可以看到tree] if (option.pagination == false && $.common.isNotEmpty(options.parentIdField)) { // 构建tree var tree = { idField: options.uniqueId, treeShowField: options.uniqueId, parentIdField: options.parentIdField, rowStyle: function (row, index) { return classes = [ 'bg-blue', 'bg-green', 'bg-red' ]; }, onPostBody: function onPostBody() { var columns = $.btTable.bootstrapTable('getOptions').columns; if (columns) { // 查看是否默认展开 var initialState = 'collapsed'; if (typeof (Storage) !== 'undefined') { initialState = localStorage.getItem('initialState'); } $.btTable.treegrid({ //initialState: 'collapsed',// 所有节点都折叠 //initialState: 'expanded',// 所有节点都展开 initialState: initialState,// 所有节点都保留上次的效果 treeColumn: 1, // 默认为第三个 // expanderExpandedClass: 'glyphicon glyphicon-minus', //图标样式 // expanderCollapsedClass: 'glyphicon glyphicon-plus', onChange: function () { $.btTable.bootstrapTable('resetWidth'); } }); } }, }; $.extend(option, tree); } $.btTable.bootstrapTable(option); }, // 查询条件 queryParams: function(params) { var curParams = { // 传递参数查询参数 pageSize: params.limit, page: params.offset / params.limit + 1, searchValue: params.search, orderByColumn: params.sort, isAsc: params.order }; var currentId = $.common.isEmpty($.table._option.formId) ? 'search_form' : $.table._option.formId; return $.extend(curParams, $.common.formToJSON(currentId)); }, // 请求获取数据后处理回调函数 responseHandler: function(res) { if (typeof $.table._option.responseHandler == "function") { $.table._option.responseHandler(res); } return { rows: res.data, total: res.total }; }, // 初始化事件 initEvent: function(data) { // 触发行点击事件 加载成功事件 $.btTable.on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table load-success.bs.table", function () { // 工具栏按钮控制 var rows = $.common.isEmpty($.table._option.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns($.table._option.uniqueId); // 非多个禁用 $('#' + $.table._option.toolbar + ' .multiple').toggleClass('disabled', !rows.length); // 非单个禁用 $('#' + $.table._option.toolbar + ' .single').toggleClass('disabled', rows.length!=1); }); // 绑定选中事件、取消事件、全部选中、全部取消 $.btTable.on("check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table", function (e, rows) { // 复选框分页保留保存选中数组 var rowIds = $.table.affectedRowIds(rows); if ($.common.isNotEmpty($.table._option.rememberSelected) && $.table._option.rememberSelected) { func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference'; selectionIds = _[func](selectionIds, rowIds); } }); }, // 表格销毁 destroy: function (tableId) { var currentId = $.common.isEmpty(tableId) ? $.table._option.id : tableId; $("#" + currentId).bootstrapTable('destroy'); }, // 图片预览 imageView: function (value, height, width, target) { if ($.common.isEmpty(width)) { width = 'auto'; } if ($.common.isEmpty(height)) { height = 'auto'; } // blank or self var _target = $.common.isEmpty(target) ? 'self' : target; if ($.common.isNotEmpty(value)) { return $.common.sprintf("<img class='img-circle img-xs' data-height='%s' data-width='%s' data-target='%s' src='%s'/>", width, height, _target, value); } else { return $.common.nullToStr(value); } }, // 搜索-默认为 search_form search: function(formId, data) { var currentId = $.common.isEmpty(formId) ? 'search_form' : formId; var params = $.btTable.bootstrapTable('getOptions'); params.queryParams = function(params) { // 获取所有搜索的form元素 var search = $.common.formToJSON(currentId); // 如传递data则追加进search中 if ($.common.isNotEmpty(data)) { $.each(data, function (key) { search[key] = data[key]; }); } search.pageSize = params.limit; search.page = params.offset / params.limit + 1; search.searchValue = params.search; search.orderByColumn = params.sort; search.isAsc = params.order; return search; } $.btTable.bootstrapTable('refresh', params); }, // 导出数据 export: function(formId) { $.modal.confirm("确定导出所有数据吗?", function() { var currentId = $.common.isEmpty(formId) ? 'search_form' : formId; window.open($.table._option.exportUrl + '?' +$("#" + currentId).serialize()); }); }, // 设置排序 sort: function(obj) { var url = $.table._option.sortUrl; var data = {"id": $(obj).data('id'), "sort": $(obj).val()}; $.operate.submit(url, "post", "json", data); }, // 刷新表格 refresh: function() { $.btTable.bootstrapTable('refresh', { silent: true }); }, // 显示表格指定列 showColumn: function(column) { $.btTable.bootstrapTable('showColumn', column); }, // 隐藏表格指定列 hideColumn: function(column) { $.btTable.bootstrapTable('hideColumn', column); }, // 查询表格指定列值 selectColumns: function(column) { var rows = $.map($.btTable.bootstrapTable('getSelections'), function (row) { return row[column]; }); if ($.common.isNotEmpty($.table._option.rememberSelected) && $.table._option.rememberSelected) { rows = rows.concat(selectionIds); } return $.common.uniqueFn(rows); }, // 获取当前页选中或者取消的行ID affectedRowIds: function(rows) { var column = $.common.isEmpty($.table._option.uniqueId) ? $.table._option.columns[1].field : $.table._option.uniqueId; var rowIds; if ($.isArray(rows)) { rowIds = $.map(rows, function(row) { return row[column]; }); } else { rowIds = [rows[column]]; } return rowIds; }, // 查询表格首列值 selectFirstColumns: function() { var rows = $.map($.btTable.bootstrapTable('getSelections'), function (row) { return row[$.table._option.columns[1].field]; }); if ($.common.isNotEmpty($.table._option.rememberSelected) && $.table._option.rememberSelected) { rows = rows.concat(selectionIds); } return $.common.uniqueFn(rows); }, }, // 表单封装处理 form: { // 表单重置 reset: function(formId) { var currentId = $.common.isEmpty(formId) ? 'search_form' : formId; $("#" + currentId)[0].reset(); // 重置select2 $('select.select2').val(null).trigger("change"); // 刷新表格 $.btTable.bootstrapTable('refresh'); }, }, // 弹出层封装处理 modal: { // 消息提示前显示图标(通常不会单独前台调用) icon: function (type) { var icon = ""; if (type == "warning") { icon = 0; } else if (type == "success") { icon = 1; } else if (type == "error") { icon = 2; } else { icon = 3; } return icon; }, // 消息提示(第一个参数为内容,第二个为类型,通过类型调用不同的图标效果) [warning/success/error] msg: function(content, type) { if (type != undefined) { layer.msg(content, {icon: $.modal.icon(type), time: 1500, anim: 5, shade: [0.3]}); } else { layer.msg(content); } }, // 错误消息 msgError: function(content) { $.modal.msg(content, "error"); }, // 成功消息 msgSuccess: function(content) { $.modal.msg(content, "success"); }, // 警告消息 msgWarning: function(content) { $.modal.msg(content, "warning"); }, // 弹出提示 alert: function(content, type, callback) { layer.alert(content, { icon: $.modal.icon(type), title: "系统提示", btn: ['确认'], btnclass: ['btn btn-primary'], }, callback); }, // 错误提示 alertError: function(content, callback) { $.modal.alert(content, "error", callback); }, // 成功提示 alertSuccess: function(content, callback) { $.modal.alert(content, "success", callback); }, // 警告提示 alertWarning: function(content, callback) { $.modal.alert(content, "warning", callback); }, // 确认窗体 confirm: function (content, callBack) { layer.confirm(content, { icon: 3, title: "系统提示", btn: ['确认', '取消'] }, function (index) { layer.close(index); callBack(true); }); }, // 消息提示并刷新父窗体 msgReload: function(msg, type) { layer.msg(msg, { icon: $.modal.icon(type), time: 500, shade: [0.1, '#8F8F8F'] }, function() { $.modal.reload(); }); }, // 弹出层指定宽度 open: function (title, url, width, height, callback) { // 如果是移动端,就使用自适应大小弹窗 if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) { width = 'auto'; height = 'auto'; } if ($.common.isEmpty(title)) { title = false; } if ($.common.isEmpty(width)) { width = 800; } if ($.common.isEmpty(height)) { height = ($(window).height() - 50); } if ($.common.isEmpty(callback)) { // 当前层索引参数(index)、当前层的DOM对象(layero) callback = function(index, layero) { //var iframeWin = layero.find('iframe')[0]; //iframeWin.contentWindow.submitHandler(index, layero); // 获取弹出层中的form表单元素 var formSubmit=layer.getChildFrame('form', index); // 获取表单中的提交按钮(在我的表单里第一个button按钮就是提交按钮,使用find方法寻找即可) var submited = formSubmit.find('.form-builder-submit').find('button')[0]; // 触发点击事件,会对表单进行验证,验证成功则提交表单,失败则返回错误信息 submited.click(); //window.parent.location.reload(); //location.reload(); } } layer.open({ // iframe层 type: 2, // 宽高 area: [width + 'px', height + 'px'], // 固定 fix: false, // 最大最小化 maxmin: true, // 遮罩 shade: 0, // 是否允许拖拽到窗口外 moveOut: true, // 标题 title: title, // 内容 content: url, // 按钮 btn: ['确定', '关闭'], // 是否点击遮罩关闭 shadeClose: true, // 确定按钮回调方法 yes: callback, // 层弹出后的成功回调方法 success: function(layero, index){ //var body = layer.getChildFrame('body', index); //body.addClass('layer-body') //body.find('.main-sidebar').hide() //body.find('.main-header').hide() //body.find('.main-footer').hide() //body.find('.content-header').hide() //body.find('.content .search').hide() //body.find('.content-wrapper').hide() }, // 右上角关闭按钮触发的回调 cancel: function(index) { return true; } }); }, // 弹出层指定参数选项 openOptions: function (options) { var _url = $.common.isEmpty(options.url) ? "/404.html" : options.url; var _title = $.common.isEmpty(options.title) ? "系统窗口" : options.title; var _width = $.common.isEmpty(options.width) ? "800" : options.width; var _height = $.common.isEmpty(options.height) ? ($(window).height() - 50) : options.height; var _btn = ['<i class="fa fa-check"></i> 确认', '<i class="fa fa-close"></i> 关闭']; if ($.common.isEmpty(options.yes)) { options.yes = function(index, layero) { options.callBack(index, layero); } } layer.open({ type: 2, maxmin: true, shade: 0.3, title: _title, fix: false, area: [_width + 'px', _height + 'px'], content: _url, shadeClose: $.common.isEmpty(options.shadeClose) ? true : options.shadeClose, skin: options.skin, btn: $.common.isEmpty(options.btn) ? _btn : options.btn, yes: options.yes, cancel: function () { return true; } }); }, // 弹出层全屏 openFull: function (title, url, width, height) { //如果是移动端,就使用自适应大小弹窗 if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) { width = 'auto'; height = 'auto'; } if ($.common.isEmpty(title)) { title = false; } if ($.common.isEmpty(url)) { url = "/404.html"; } if ($.common.isEmpty(width)) { width = 800; } if ($.common.isEmpty(height)) { height = ($(window).height() - 50); } var index = layer.open({ type: 2, area: [width + 'px', height + 'px'], fix: false, //不固定 maxmin: true, shade: 0.3, title: title, content: url, btn: ['确定', '关闭'], // 弹层外区域关闭 shadeClose: true, yes: function(index, layero) { var iframeWin = layero.find('iframe')[0]; iframeWin.contentWindow.submitHandler(index, layero); }, cancel: function(index) { return true; } }); layer.full(index); }, // 重新加载 reload: function () { parent.location.reload(); }, // 关闭窗体 close: function () { var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); }, }, // 操作封装处理 operate: { // 修改信息 edit: function(id) { var url = $.operate.editUrl(id) if ($.table._option.layerOpen == "1") { // 通过参数隐藏左侧和顶部等数据 if (url.indexOf('?') != -1) { url = url + '&_layer=1' } else { url = url + '?_layer=1' } // 弹窗打开要添加的地址 $.modal.open("修改", url); } else { // 当前窗口打开要添加的地址 $.common.jump(url); } }, // 修改访问的地址 editUrl: function(id) { var url = ""; if ($.common.isNotEmpty(id)) { url = $.table._option.editUrl.replace("__id__", id); } else { var id = $.common.isEmpty($.table._option.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns($.table._option.uniqueId); if (id.length == 0) { $.modal.alertWarning("请至少选择一条记录"); return; } url = $.table._option.editUrl.replace("__id__", id); } // 获取搜索信息 var back = $.common.serializeRemoveNull($("#search_form").serialize()); back = back ? '&back_url=' + encodeURIComponent(back) : ''; return url + back; }, // 添加信息 add: function(id) { var url = $.operate.addUrl(id) if ($.table._option.layerOpen == "1") { // 通过参数隐藏左侧和顶部等数据 if (url.indexOf('?') != -1) { url = url + '&_layer=1' } else { url = url + '?_layer=1' } // 弹窗打开要添加的地址 $.modal.open("添加", url); } else { // 当前窗口打开要添加的地址 $.common.jump(url); } }, // 添加访问的地址 addUrl: function(id) { var url = $.common.isEmpty(id) ? $.table._option.addUrl.replace("__id__", "") : $.table._option.addUrl.replace("__id__", id); // 获取搜索信息 var back = $.common.serializeRemoveNull($("#search_form").serialize()); if (url.indexOf('?') != -1) { back = back ? '&back_url=' + encodeURIComponent(back) : ''; } else { back = back ? '?back_url=' + encodeURIComponent(back) : ''; } return url + back; }, // 删除信息 remove: function(id) { $.modal.confirm("确定删除该条数据吗?", function() { var url = $.common.isEmpty(id) ? $.table._option.delUrl : $.table._option.delUrl.replace("__id__", id); var data = { "id": id }; $.operate.submit(url, "post", "json", data); }); }, // 批量删除信息 removeAll: function() { var rows = $.common.isEmpty($.table._option.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns($.table._option.uniqueId); if (rows.length == 0) { $.modal.alertWarning("请至少选择一条记录"); return; } $.modal.confirm("确认要删除选中的" + rows.length + "条数据吗?", function() { var url = $.table._option.delUrl.replace("__id__", rows.join()); var data = { "id": rows.join() }; $.operate.submit(url, "post", "json", data); }); }, // 修改状态 state: function(id, url) { $.modal.confirm("确认要更改状态吗?", function () { var data = {"id": id}; $.operate.submit(url, "post", "json", data); }); }, // 代码生成 build: function(id, url) { $.modal.confirm("确定要生成代码吗?生成代码会覆盖原有的控制器、模型和验证器文件<br>注意:原有文件会被重命名留做备份", function() { if ($.common.isEmpty(id)) { var id = $.common.isEmpty($.table._option.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns($.table._option.uniqueId); if (id.length == 0) { $.modal.alertWarning("请至少选择一条记录"); return; } } var data = {"id": id[0]}; $.operate.submit(url, "post", "json", data); }); }, // 生成菜单规则 makeRule: function (url) { $.modal.confirm("确定要生成菜单规则吗,我们会根据模块的参数生成列表、新增、新增保存、修改、修改保存、删除、批量删除、导出、状态、排序 等规则", function () { var id = $.table.selectFirstColumns(); if (id.length == 0) { $.modal.alertWarning("请至少选择一条记录"); return; } var data = {"id": id[0]}; $.operate.submit(url, "post", "json", data); }); }, // 数据库备份+优化+修复 database: function(url, title) { var rows = $.common.isEmpty($.table._option.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns($.table._option.uniqueId); if (rows.length == 0) { $.modal.alertWarning("请至少选择一条记录"); return; } $.modal.confirm("确认要" + title + "选中的" + rows.length + "条数据吗?", function () { var data = { "id": rows.join() }; $.operate.submit(url, "post", "json", data); }); }, // 提交数据 submit: function(url, type, dataType, data, callback) { var config = { url: url, type: type, dataType: dataType, data: data, beforeSend: function () { // "正在处理中,请稍后..." }, success: function(result) { if (typeof callback == "function") { callback(result); } $.operate.ajaxSuccess(result); } }; $.ajax(config) }, // 保存信息 刷新表格 save: function(url, data, callback) { var config = { url: url, type: "post", dataType: "json", data: data, success: function(result) { if (typeof callback == "function") { callback(result); } $.operate.successCallback(result); } }; $.ajax(config) }, // 成功回调执行事件(父窗体静默更新) successCallback: function(result) { if (result.code == 1) { var parent = window.parent; $.modal.close(); parent.toastr.success(result.msg); // toastr提示 // parent.$.modal.msgSuccess(result.msg); // 消息提示 parent.$.table.refresh(); } else { $.modal.alertError(result.msg); } }, // 保存结果弹出msg刷新table表格 ajaxSuccess: function (result) { if (result.error == 0 || result.code == 1) { toastr.success(result.msg); // toastr提示 //$.modal.msgSuccess(result.msg); // 消息提示 $.table.refresh(); } else { $.modal.alertError(result.msg); } }, // 展开/折叠列表树 treeStatus: function (result) { // 上次展开则增加样式 var initialState = 'collapsed'; if (typeof (Storage) !== 'undefined') { initialState = localStorage.getItem('initialState'); } if (initialState == 'expanded') { $('.treeStatus').addClass('expandAll'); } if ($('.treeStatus').hasClass('expandAll')) { $.btTable.treegrid('collapseAll'); $('.treeStatus').removeClass('expandAll'); // 更新 if (typeof (Storage) !== 'undefined') { localStorage.setItem('initialState', 'collapsed'); } } else { $.btTable.treegrid('expandAll'); $('.treeStatus').addClass('expandAll'); // 更新 if (typeof (Storage) !== 'undefined') { localStorage.setItem('initialState', 'expanded'); } } }, // 批量添加栏目 batchAdd: function(url) { if ($.table._option.layerOpen == "1") { // 通过参数隐藏左侧和顶部等数据 if (url.indexOf('?') != -1) { url = url + '&_layer=1' } else { url = url + '?_layer=1' } // 弹窗打开要添加的地址 $.modal.open("批量添加", url); } else { // 当前窗口打开要添加的地址 $.common.jump(url); } }, }, // 通用方法封装处理 common: { // 判断字符串是否为空 isEmpty: function (value) { if (value == null || this.trim(value) == "") { return true; } return false; }, // 判断一个字符串是否为非空串 isNotEmpty: function (value) { return !$.common.isEmpty(value); }, // 空格截取 trim: function (value) { if (value == null) { return ""; } return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, ""); }, // 比较两个字符串(大小写敏感) equals: function (str, that) { return str == that; }, // 比较两个字符串(大小写不敏感) equalsIgnoreCase: function (str, that) { return String(str).toUpperCase() === String(that).toUpperCase(); }, // 将字符串按指定字符分割 split: function (str, sep, maxLen) { if ($.common.isEmpty(str)) { return null; } var value = String(str).split(sep); return maxLen ? value.slice(0, maxLen - 1) : value; }, // 字符串格式化(%s ) sprintf: function (str) { var args = arguments, flag = true, i = 1; str = str.replace(/%s/g, function () { var arg = args[i++]; if (typeof arg === 'undefined') { flag = false; return ''; } return arg; }); return flag ? str : ''; }, // 数组去重 uniqueFn: function(array) { var result = []; var hashObj = {}; for (var i = 0; i < array.length; i++) { if (!hashObj[array[i]]) { hashObj[array[i]] = true; result.push(array[i]); } } return result; }, // 获取form下所有的字段并转换为json对象 formToJSON: function(formId) { var json = {}; $.each($("#" + formId).serializeArray(), function(i, field) { json[field.name] = field.value; }); return json; }, // pjax跳转页 jump: function (url) { $.pjax({url: url, container: '.content-wrapper'}) //window.location.href = url; }, // 序列化表单,不含空元素 serializeRemoveNull: function (serStr) { // return serStr.split("&").filter(str => !str.endsWith("=")).join("&"); // 不兼容ie return serStr.split("&").filter(function (item) { var itemArr = item.split('='); if(itemArr[1]){ return item; } } ).join("&"); }, } }); })(jQuery); ``` \static\plugins\siyucms.js ``` // daterangepicker 动态元素追加后重新绑定(列表搜索) $(document).on('mouseover', "input[daterange='true']", function () { $(this).daterangepicker( { autoUpdateInput: false, // 自动填充日期 showDropdowns: true, // 年月份下拉框 timePicker: true, // 显示时间 timePicker24Hour: true, // 时间制 timePickerSeconds: true, // 时间显示到秒 ranges: { '今天': [moment(), moment()], '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], '上周': [moment().subtract(6, 'days'), moment()], '前30天': [moment().subtract(29, 'days'), moment()], '本月': [moment().startOf('month'), moment().endOf('month')], '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')], '今年第一天':moment().startOf('year').format('YYYY-MM-DD'), '去年第一天':moment().subtract(1,'year').startOf('year').format('YYYY-MM-DD') }, locale: { format: "YYYY/MM/DD", applyLabel: '确定', // 确定按钮文本 cancelLabel: '取消', // 取消按钮文本 customRangeLabel: '自定义', } } ).on('cancel.daterangepicker', function (ev, picker) { $(this).val(""); }).on('apply.daterangepicker', function (ev, picker) { $(this).val(picker.startDate.format('YYYY-MM-DD') + " 至 " + picker.endDate.format('YYYY-MM-DD')); }); }) // 列表图片鼠标移上跟随效果(兼容ajax分页) $(document).on('mouseover', '.image_preview', function (e) { var image = $(this).attr("src"); if (image != "") { var zoomView = $('<img src="' + image + '" id="zoomView" />'); // 建立图片查看框 $(this).after(zoomView); $("#zoomView").fadeIn(100); $("#zoomView").css({"top": (e.pageY - 250) + "px", "left": (e.pageX - 210) + "px"}); //注意得在CSS文件中将其设置为绝对定位 } }) $(document).on('mousemove', '.image_preview', function (e) { var image = $(this).attr("image"); if (image != "") { $("#zoomView").css({"top": (e.pageY - 250) + "px", "left": (e.pageX - 210) + "px"}); //鼠标移动时及时更新图片查看框的坐标 } }) $(document).on('mouseout', '.image_preview', function (e) { var image = $(this).attr("image"); if (image != "") { $("#zoomView").remove(); //鼠标移出时删除之前建立的图片查看框 } }) // 常规表单提交转变成ajax $(document).on("submit", 'form:not([data-pjax])', function () { var _this = $(this); // 判断是否开启了提交确认 if (typeof ($(this).attr("submit_confirm")) == "undefined") { // 不需要提交确认,直接提交表单 formSubmit(_this); } else { // 需要确认提示 $.modal.confirm('确定要提交吗?', function () { formSubmit(_this); }) } return false; // 阻止表单默认提交 }) // 捐赠 $(document).on("click", '.juanzeng', function () { $.modal.open('捐赠', "/static/admin/images/shoukuan.png", 450, 533); }) // 多图删除 $(document).on('click', '.remove_images', function () { var remove = $(this).parent().parent().parent(); remove.remove(); }) // 多图上移 $(document).on('click', '.move_up_images', function () { var move = $(this).parent().parent().parent(); move.prev().insertAfter(move); }) // 多图下移 $(document).on('click', '.move_down_images', function () { var move = $(this).parent().parent().parent(); move.next().insertBefore(move); }) // 返回顶部显示 $(window).scroll(function () { if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) { $('#totop').fadeIn(500) } else { $('#totop').fadeOut(500) } }); // 返回顶部点击 $(document).on("click", '#totop', function (e) { // 防止打开URL e.preventDefault(); $('html,body').animate({ scrollTop: 0 }, 300) }); // pjax 执行完成后执行的方法 $(document).on('pjax:complete', function () { // 首页重新请求远程ad if ($(".main_ad").length > 0) { $.getScript("https://www.siyucms.com/ad.js"); } // tag 标签 if ($(".tags").length > 0) { $('.tags').tagsInput({ 'width': 'auto', 'height': 'auto', 'placeholderColor': '#666666', 'defaultText': '添加标签', }); } // tooltip 提示 $('[data-toggle="tooltip"]').tooltip() // 更改网站标题 changeWebTitle(); }) $(function () { // 返回上一页时重新触发pjax,防止加载重复的bootstrap-table window.addEventListener("popstate", function (e) { $.pjax.reload('.content-wrapper'); }, false); // 左侧菜单点击 /*$(".main-sidebar .nav .nav-treeview a.nav-link").click(function () { if($(this).attr('link') !== '#'){ $(".main-sidebar .nav .nav-treeview a.nav-link").removeClass('active'); $(this).addClass('active'); $(this).parents('.nav-item').last().siblings().children('a').removeClass('active') $(this).parents('.nav-item').last().children('a').addClass('active') } })*/ // 左侧菜单高亮 $('.main-sidebar .nav .nav-treeview a.nav-link').on('click', function () { if ($(this).attr('link') !== '#') { $(".main-sidebar .nav .nav-treeview a.nav-link").removeClass('active'); $(this).addClass('active'); $(this).parents('.nav-item').last().siblings().children('a').removeClass('active') $(this).parents('.nav-item').last().children('a').addClass('active') } // 小屏幕上点击左边菜单栏按钮,模拟点击 xs: 480,sm: 768,md: 992,lg: 1200 if ($(window).width() < 992) { // 触发左边菜单栏按钮点击事件,关闭菜单栏 $("[data-widget='pushmenu']").trigger('click'); } }); // 刷新后匹配当前URL和标题 $(window).on('load', function () { // 获取当前页面面包导航标题 var _title = $(".content-header").find("h1").clone(); _title.find(':nth-child(n)').remove(); if (_title.length > 0) { _title = _title.html().trim(); } // 循环匹配 $('.sidebar .nav-sidebar a.nav-link').each(function () { //$(this).children('p').find(':nth-child(n)').remove() var _html = $(this).children('p').html().replace("|—", "").replace(" ", "").trim() if (this.href !== '#' && _html == _title) { // 打开对应菜单 $(this).addClass('active') .closest('.nav-treeview').show() // 打开二级ul .closest('.has-treeview').addClass('menu-open') // 打开一级li .children('a.nav-link').addClass('active'); // 高亮一级a // 判断当前所属的是第几个 var _index = $(this).parents('.nav-item').last().data('item') // 执行点击动作 $(".js_left_menu li").eq(_index).click(); } }); // 改变网站标题 changeWebTitle(); }); // tag 标签 if ($(".tags").length > 0) { $('.tags').tagsInput({ 'width': 'auto', 'height': 'auto', 'placeholderColor': '#666666', 'defaultText': '添加标签', }); } // tooltip 提示 $('[data-toggle="tooltip"]').tooltip() // 多级联动 $('.js_linkage').change(function () { var value = $(this).val(); // 当前下拉框选中的值 var nextLevelId = $(this).data('next_level_id'); // 下一级别下拉框的id var ajaxUrl = $(this).data('ajax_url'); // 请求地址 // 下级联动菜单恢复默认 if (nextLevelId != '') { $('#' + nextLevelId).html('<option value="">' + $(this).data('placeholder') + '</option>'); var hasNextLevel = $('#' + nextLevelId).data('next_level_id'); if (hasNextLevel) { $('#' + hasNextLevel).html('<option value="">' + $(this).data('placeholder') + '</option>'); hasNextLevel = $('#' + hasNextLevel).data('next-next_level_id-id'); if (hasNextLevel) { $('#' + hasNextLevel).html('<option value="">' + $(this).data('placeholder') + '</option>'); } } } if (value != '') { // 获取数据 $.ajax({ url: ajaxUrl, type: 'POST', dataType: 'json', data: { level: $(this).data('next_level'), // 下一级别(废弃) pid: value, // 当前下拉框选中的值 model: $(this).data('model'), // 模型名称 key: $(this).data('key'), // 关联模型的主键 keyValue: $(this).data('key_value'), // 要展示的字段 pidFieldName: $(this).data('pid_field_name'), // 关联模型的父级id字段名 }, success: function (res) { if (res.code == '1') { var list = res.list; if (list) { for (var item in list) { $('#' + nextLevelId).append("<option value='" + list[item].key + "'>" + list[item].value + "</option>"); } } } else { $.modal.alertError(res.msg); } } }) } }); }) // ============================================= // 表单提交 function formSubmit($this) { $this.ajaxSubmit(function (result) { var url = window.location.href; if (url.indexOf("_layer=1") >= 0) { // layer 弹层 $.operate.successCallback(result); } else { // 普通提交跳转 if (result.code == 1) { // 提交成功 $.modal.alertSuccess(result.msg, function (index) { layer.close(index); $.common.jump(result.url); }); } else { // 提交失败 $.modal.alertError(result.msg); } } }); } // pjax 刷新当前页 function pjaxReplace(url) { $.pjax({url: url, container: '.content-wrapper'}) } // 转换日期格式(时间戳转换为datetime格式) function changeDateFormat(cellval) { if (cellval == '') { return '-'; } if (cellval != null && cellval != undefined) { if (cellval.toString().indexOf("-") >= 0) { return cellval; } } var dateVal = cellval * 1000; if (cellval != null) { var date = new Date(dateVal); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds; } } // pjax 改变网站标题 function changeWebTitle() { // 获取当前页的名称 var _title = $(".content-header").find("h1").clone(); _title.find(':nth-child(n)').remove(); if (_title.length > 0) { _title = _title.html().trim(); } else { _title = ''; } // 获取网站标题 var title = $(document).attr('title').split(' | '); // 设置网站标题 if (title[1] != _title && $.common.isNotEmpty(_title)) { $(document).attr('title', title[0] + ' | ' + _title); } } // 拆分字符串为数组并判断是否包含某个元素 function checkValInStr(val, str) { var strArr = str.toString().split(','); if ($.inArray(val, strArr) >= 0) { return true; } else { return false; } } ```