• JQuery EasyUi之界面设计——通用的JavaScript


    所谓磨刀不误砍柴工,先写点通用的代码,后面开发起来效率就高多了。多余的话就不敲了,先简单介绍介绍吧。


    时间格式化

    对于序列化JSON,我喜欢用JSON.NET,为了方便,我定义了一个扩展方法,如下面代码:

       1:          /// <summary>
       2:          /// 将对象序列化为JSON数据
       3:          /// </summary>
       4:          /// <param name="instance"></param>
       5:          /// <returns></returns>
       6:          public static string ToJson(this object instance)
       7:          {
       8:              return JsonConvert.SerializeObject(instance);
       9:          }

    那么序列化JOSN输出那么就方便多了,如下面代码:

       1:                                      var info = from a in db.TB_KTVAndConcert
       2:                                                 join b in db.TB_City on a.Cityid equals b.ID
       3:                                                 where a.AttributeCode == "AttrubuteCode".GetRequest()
       4:                                                 orderby a.Cityid
       5:                                                 select new
       6:                                                 {
       7:                                                     a.CreateDate,
       8:                                                     a.Defaultflag,
       9:                                                     a.ID,
      10:                                                     a.Name,
      11:                                                     a.Cityid,
      12:                                                     b.CityName,
      13:                                                     a.Displayindex
      14:                                                 };
      15:                                      if ("CityID".GetRequest().IsNotEmpty())
      16:                                      {
      17:                                          if (MyRegex.IsNumberRegex("CityID".GetRequest()))
      18:                                          {
      19:                                              int cityId = Convert.ToInt32("CityID".GetRequest());
      20:                                              info = info.Where(p => p.Cityid == cityId);
      21:                                          }
      22:                                      }
      23:                                      context.Response.Write(info.OrderByDescending(p => p.Defaultflag).ThenBy(p => p.Displayindex).ToJson());

    序列化JSON是可以了,但是前台显示DateTime类型数据时显示就有问题了,也就是获取不到想要的格式化字符串。解决这个问题有两种方式,方式一就是定义一个C#方法来返回格式化时间字符串,关键部分代码如下:

       1:                                                 select new
       2:                                                 {
       3:                                                     CreateDate = a.CreateDate.GetDateTimeString(),
       4:                                                     a.Defaultflag,
       5:                                                     a.ID,
       6:                                                     a.Name,
       7:                                                     a.Cityid,
       8:                                                     b.CityName,
       9:                                                     a.Displayindex
      10:                                                 };

    这样虽然可以,但是如果我想统一在浏览器端处理呢?于是封装下面的函数:

       1:  //时间格式化
       2:  Date.prototype.format = function (format) {
       3:      if (!format) {
       4:          format = "yyyy-MM-dd hh:mm:ss";
       5:      }
       6:      var o = {
       7:          "M+": this.getMonth() + 1, // month
       8:          "d+": this.getDate(), // day
       9:          "h+": this.getHours(), // hour
      10:          "m+": this.getMinutes(), // minute
      11:          "s+": this.getSeconds(), // second
      12:          "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
      13:          "S": this.getMilliseconds()
      14:          // millisecond
      15:      };
      16:      if (/(y+)/.test(format)) {
      17:          format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      18:      }
      19:      for (var k in o) {
      20:          if (new RegExp("(" + k + ")").test(format)) {
      21:              format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      22:          }
      23:      }
      24:      return format;
      25:  };
      26:  function fomatDate(str) {
      27:      return (new Date(parseInt(str.substring(str.indexOf('(') + 1, str.indexOf(')'))))).format("yyyy-MM-dd hh:mm:ss");
      28:  }

      前台调用:

       1:          function formatCreateDate(value, row, index) {
       2:   
       3:              return fomatDate(row.CreateDate);
       4:   
       5:          }

    显示效果:

    image


    消息框

    弹出框以及系统消息框

       1:  function showMsg(title, msg, isAlert) {
       2:      if (isAlert !== undefined && isAlert) {
       3:          $.messager.alert(title, msg);
       4:      } else {
       5:          $.messager.show({
       6:              title: title,
       7:              msg: msg,
       8:              showType: 'show'
       9:          });
      10:      }
      11:  }

     

    确认框

       1:  function showConfirm(title, msg, callback) {
       2:      $.messager.confirm(title, msg, function (r) {
       3:          if (r) {
       4:              if (jQuery.isFunction(callback))
       5:                  callback.call();
       6:          }
       7:      });
       8:  }

    进度框

       1:  function showProcess(isShow, title, msg) {
       2:      if (!isShow) {
       3:          $.messager.progress('close');
       4:          return;
       5:      }
       6:      var win = $.messager.progress({
       7:          title: title,
       8:          msg: msg
       9:      });
      10:  }

    例如在表单提交时,为了防止重复提交,会显示一个进度框。提交完成时,关闭进度框并提示操作信息:

       1:  function submitForm(url) {
       2:      $('#ff').form('submit', {
       3:          url: (url === undefined ? "/Ajax/Common.ashx" : url) + "?Type=" + typeCode,
       4:          onSubmit: function () {
       5:              var flag = $(this).form('validate');
       6:              if (flag) {
       7:                  showProcess(true, '温馨提示', '正在提交数据...');
       8:              }
       9:              return flag
      10:          },
      11:          success: function (data) {
      12:              showProcess(false);
      13:              if (data == 1) {
      14:                  top.showMsg('温馨提示', '提交成功!');
      15:                  if (parent !== undefined) {
      16:                      if ($.isFunction(window.reloadParent)) {
      17:                          reloadParent.call();
      18:                      } else {
      19:                          parent.$("#tt").datagrid('reload');
      20:                          parent.closeMyWindow();
      21:                      }
      22:                  }
      23:              } else {
      24:                  $.messager.alert('温馨提示', data);
      25:              }
      26:          },
      27:          onLoadError: function () {
      28:              showProcess(false);
      29:              $.messager.alert('温馨提示', '由于网络或服务器太忙,提交失败,请重试!');
      30:          }
      31:      });
      32:  }
    关键页面代码如下:
       1:      <div class="easyui-layout" style="text-align: left; height: 270px;" fit="true">
       2:   
       3:          <div region="center" border="false" style="padding: 10px; background: #fff; border: 1px solid #ccc;">
       4:   
       5:              <form id="ff" method="post">
       6:   
       7:              <input type="hidden" name="id" value="" />
       8:   
       9:              <table border="0" cellpadding="0" cellspacing="0">
      10:   
      11:                  <tr>
      12:   
      13:                      <td>
      14:   
      15:                          <label for="AdminLogin">
      16:   
      17:                              登录名:</label>
      18:   
      19:                      </td>
      20:   
      21:                      <td>
      22:   
      23:                          <input class="easyui-validatebox" style=" 300px;" type="text" required="true"
      24:   
      25:                              validtype="length[0,20]" name="AdminLogin"></input>
      26:   
      27:                      </td>
      28:   
      29:                  </tr>
      30:   
      31:                  <tr>
      32:   
      33:                      <td>
      34:   
      35:                          <label for="RoleID">
      36:   
      37:                              所属角色:</label>
      38:   
      39:                      </td>
      40:   
      41:                      <td>
      42:   
      43:                          <input class="easyui-combobox" valuefield="ID" textfield="RoleName" panelheight="auto"
      44:   
      45:                              editable="false" style=" 300px;" url="/Ajax/Common.ashx?Type=GetRoles"
      46:   
      47:                              required="true" name="RoleID"></input>
      48:   
      49:                      </td>
      50:   
      51:                  </tr>
      52:   
      53:                  <tr>
      54:   
      55:                      <td colspan="2" style='color: Red'>
      56:   
      57:                          在编辑时,输入管理员密码表示重新设置密码。
      58:   
      59:                      </td>
      60:   
      61:                  </tr>
      62:   
      63:                  <tr>
      64:   
      65:                      <td>
      66:   
      67:                          <label for="AdminPassword">
      68:   
      69:                              密码:</label>
      70:   
      71:                      </td>
      72:   
      73:                      <td>
      74:   
      75:                          <input class="easyui-validatebox" style=" 300px;" type="text" validtype="length[6,20]"
      76:   
      77:                              id='txtPassword' name="AdminPassword"></input>
      78:   
      79:                      </td>
      80:   
      81:                  </tr>
      82:   
      83:                  <tr>
      84:   
      85:                      <td>
      86:   
      87:                          <label for="AdminPassword2">
      88:   
      89:                              确认密码:</label>
      90:   
      91:                      </td>
      92:   
      93:                      <td>
      94:   
      95:                          <input class="easyui-validatebox" style=" 300px;" type="text" validtype="length[6,20]"
      96:   
      97:                              id='txtPassword2' name="AdminPassword2"></input>
      98:   
      99:                      </td>
     100:   
     101:                  </tr>
     102:   
     103:                  <tr>
     104:   
     105:                      <td>
     106:   
     107:                          <label for="Defatulflag">
     108:   
     109:                              是否上架:</label>
     110:   
     111:                      </td>
     112:   
     113:                      <td>
     114:   
     115:                          <input type="checkbox" name="Defatulflag" class="easyui-validatebox" type="text"
     116:   
     117:                              required="true" value="1" />
     118:   
     119:                      </td>
     120:   
     121:                  </tr>
     122:   
     123:              </table>
     124:   
     125:              </form>
     126:   
     127:          </div>
     128:   
     129:          <div region="south" border="false" style="text-align: right; padding: 5px 5px 5px 0;">
     130:   
     131:              <a class="easyui-linkbutton" iconcls="icon-save" href="javascript:void(0)" onclick="javascript:submitForm();">
     132:   
     133:                  提交</a> 
     134:   
     135:          </div>
     136:   
     137:      </div>
     138:   
     139:      <script type="text/javascript">
     140:   
     141:          $(function () {
     142:   
     143:              if (autoLoad == 1) {
     144:   
     145:                  $('#txtPassword').keypress(function () {
     146:   
     147:                      if ($(this).val().length > 0) {
     148:   
     149:                          $('#txtPassword2').validatebox({
     150:   
     151:                              required: true
     152:   
     153:                          });
     154:   
     155:                      }
     156:   
     157:                  }).change(function () {
     158:   
     159:                      if ($(this).val().length > 0) {
     160:   
     161:                          $('#txtPassword2').validatebox({
     162:   
     163:                              required: true
     164:   
     165:                          });
     166:   
     167:                      } else {
     168:   
     169:                          $('#txtPassword2').validatebox({
     170:   
     171:                              required: false
     172:   
     173:                          });
     174:   
     175:                      }
     176:   
     177:                  });
     178:   
     179:   
     180:   
     181:              } else {
     182:   
     183:                  $('#txtPassword,#txtPassword2').validatebox({
     184:   
     185:                      required: true
     186:   
     187:                  }); ;
     188:   
     189:              }
     190:   
     191:          });
     192:   
     193:      </script>
     194:   
     
    效果如下:
    image
    image
    image

    窗口

    窗口是用的非常频繁的,显示窗口:

       1:  $(function () {
       2:      $('body').append('<div id="myWindow" class="easyui-dialog" closed="true"></div>');
       3:  });
       4:  function showMyWindow(title, href, width, height, modal, minimizable, maximizable) {
       5:      $('#myWindow').window({
       6:          title: title,
       7:           width === undefined ? 600 : width,
       8:          height: height === undefined ? 400 : height,
       9:          content: '<iframe scrolling="yes" frameborder="0"  src="' + href + '" ></iframe>',
      10:          //        href: href === undefined ? null : href,
      11:          modal: modal === undefined ? true : modal,
      12:          minimizable: minimizable === undefined ? false : minimizable,
      13:          maximizable: maximizable === undefined ? false : maximizable,
      14:          shadow: false,
      15:          cache: false,
      16:          closed: false,
      17:          collapsible: false,
      18:          resizable: false,
      19:          loadingMessage: '正在加载数据,请稍等片刻......'
      20:      });
      21:  }

    关闭窗口:

       1:  function closeMyWindow() {
       2:      $('#myWindow').window('close');
       3:  }
    使用方式如下:
       1:          function onDataGridDblClickRow(rowIndex, rowData) {
       2:   
       3:              edit();
       4:   
       5:          }
       6:   
       7:          function addType() {
       8:   
       9:              showMyWindow('用户管理 | 新建', '/WebPages/RoleManagement/AdminUser_Add.aspx', 600, 320)
      10:   
      11:          }
      12:   
      13:          function edit() {
      14:   
      15:              var row = $('#tt').datagrid('getSelected');
      16:   
      17:              if (row) {
      18:   
      19:                  showMyWindow('用户管理 | 编辑', '/WebPages/RoleManagement/AdminUser_Add.aspx?ID=' + row.ID + '&autoLoad=1', 600, 320)
      20:   
      21:              } else {
      22:   
      23:                  showMsg("温馨提示", "请选择一行!");
      24:   
      25:              }
      26:   
      27:          }
    窗口弹出有本页弹出,有时由于框架页太小,经常会使用顶层窗口弹出,如:
       1:          function showSetPicWindow(adname, id) {
       2:   
       3:              top.showMyWindow(adname + " | 广告图设置", '/WebPages/ADManagement/ADPicturesManagement.aspx?TypeCode=ADPictures&ID=' + id + '&ATCode=KTVAdvert', 707, 440);
       4:   
       5:          }
    效果如下:
    image

    表单

    一个系统总是不乏表单的,自然表单的提交与赋值自然是频繁的。如果使用C#,可以通过反射减少工作量,但是我更趋向把工作量留给前台。比如提交:

       1:  function submitForm(url) {
       2:      $('#ff').form('submit', {
       3:          url: (url === undefined ? "/Ajax/Common.ashx" : url) + "?Type=" + typeCode,
       4:          onSubmit: function () {
       5:              var flag = $(this).form('validate');
       6:              if (flag) {
       7:                  showProcess(true, '温馨提示', '正在提交数据...');
       8:              }
       9:              return flag
      10:          },
      11:          success: function (data) {
      12:              showProcess(false);
      13:              if (data == 1) {
      14:                  top.showMsg('温馨提示', '提交成功!');
      15:                  if (parent !== undefined) {
      16:                      if ($.isFunction(window.reloadParent)) {
      17:                          reloadParent.call();
      18:                      } else {
      19:                          parent.$("#tt").datagrid('reload');
      20:                          parent.closeMyWindow();
      21:                      }
      22:                  }
      23:              } else {
      24:                  $.messager.alert('温馨提示', data);
      25:              }
      26:          },
      27:          onLoadError: function () {
      28:              showProcess(false);
      29:              $.messager.alert('温馨提示', '由于网络或服务器太忙,提交失败,请重试!');
      30:          }
      31:      });
      32:  }

    值得说明的是:

    1. typeCode来自母版页,为页面名。
    2. url为提交的URL。
    3. onSubmit事件会触发表单验证,如果验证通过会显示提交进度遮罩层。如果觉得不够用,可以自己扩展。
    4. success事件会关闭进度,如果提交成功会显示成功提示,如果存在父窗口,会刷新父页面DataGrid并且关闭当前窗口。当然也可以实现reloadParent函数来个性化处理。
    5. 表单id和DataGrid的id都是固定的,如果没有效果请检查id。
    6. 关于表单的这里只写了提交,赋值的代码写在母版页了,以后再说。

    页面html的提交代码如下:

       1:  <a class="easyui-linkbutton" iconcls="icon-save" href="javascript:void(0)" onclick="javascript:submitForm('/Ajax/ShortMMS_Common.ashx');">
       2:                  提交</a>

     

    有些页面可能刷新DataGrid还不够,需要刷新页面,于是可以使用下面的JS:

       1:      <script type="text/javascript">
       2:          function reloadParent() {
       3:              top.showProcess(false);
       4:              parent.showMsg('温馨提示', '提交成功');
       5:              parent.document.location.reload();
       6:          }
       7:      </script>

    最后,附上完整的JS代码:

       1:  //时间格式化
       2:  Date.prototype.format = function (format) {
       3:      if (!format) {
       4:          format = "yyyy-MM-dd hh:mm:ss";
       5:      }
       6:      var o = {
       7:          "M+": this.getMonth() + 1, // month
       8:          "d+": this.getDate(), // day
       9:          "h+": this.getHours(), // hour
      10:          "m+": this.getMinutes(), // minute
      11:          "s+": this.getSeconds(), // second
      12:          "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
      13:          "S": this.getMilliseconds()
      14:          // millisecond
      15:      };
      16:      if (/(y+)/.test(format)) {
      17:          format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      18:      }
      19:      for (var k in o) {
      20:          if (new RegExp("(" + k + ")").test(format)) {
      21:              format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      22:          }
      23:      }
      24:      return format;
      25:  };
      26:  function fomatDate(str) {
      27:      return (new Date(parseInt(str.substring(str.indexOf('(') + 1, str.indexOf(')'))))).format("yyyy-MM-dd hh:mm:ss");
      28:  }
      29:  function showMsg(title, msg, isAlert) {
      30:      if (isAlert !== undefined && isAlert) {
      31:          $.messager.alert(title, msg);
      32:      } else {
      33:          $.messager.show({
      34:              title: title,
      35:              msg: msg,
      36:              showType: 'show'
      37:          });
      38:      }
      39:  }
      40:  $(function () {
      41:      $('body').append('<div id="myWindow" class="easyui-dialog" closed="true"></div>');
      42:  });
      43:  function showMyWindow(title, href, width, height, modal, minimizable, maximizable) {
      44:      $('#myWindow').window({
      45:          title: title,
      46:           width === undefined ? 600 : width,
      47:          height: height === undefined ? 400 : height,
      48:          content: '<iframe scrolling="yes" frameborder="0"  src="' + href + '" ></iframe>',
      49:          //        href: href === undefined ? null : href,
      50:          modal: modal === undefined ? true : modal,
      51:          minimizable: minimizable === undefined ? false : minimizable,
      52:          maximizable: maximizable === undefined ? false : maximizable,
      53:          shadow: false,
      54:          cache: false,
      55:          closed: false,
      56:          collapsible: false,
      57:          resizable: false,
      58:          loadingMessage: '正在加载数据,请稍等片刻......'
      59:      });
      60:  }
      61:  function closeMyWindow() {
      62:      $('#myWindow').window('close');
      63:  }
      64:  function submitForm(url) {
      65:      $('#ff').form('submit', {
      66:          url: (url === undefined ? "/Ajax/Common.ashx" : url) + "?Type=" + typeCode,
      67:          onSubmit: function () {
      68:              var flag = $(this).form('validate');
      69:              if (flag) {
      70:                  showProcess(true, '温馨提示', '正在提交数据...');
      71:              }
      72:              return flag
      73:          },
      74:          success: function (data) {
      75:              showProcess(false);
      76:              if (data == 1) {
      77:                  top.showMsg('温馨提示', '提交成功!');
      78:                  if (parent !== undefined) {
      79:                      if ($.isFunction(window.reloadParent)) {
      80:                          reloadParent.call();
      81:                      } else {
      82:                          parent.$("#tt").datagrid('reload');
      83:                          parent.closeMyWindow();
      84:                      }
      85:                  }
      86:              } else {
      87:                  $.messager.alert('温馨提示', data);
      88:              }
      89:          },
      90:          onLoadError: function () {
      91:              showProcess(false);
      92:              $.messager.alert('温馨提示', '由于网络或服务器太忙,提交失败,请重试!');
      93:          }
      94:      });
      95:  }
      96:  function deleteConfirm() {
      97:      return showConfirm('温馨提示', '确定要删除吗?');
      98:  }
      99:  function showConfirm(title, msg, callback) {
     100:      $.messager.confirm(title, msg, function (r) {
     101:          if (r) {
     102:              if (jQuery.isFunction(callback))
     103:                  callback.call();
     104:          }
     105:      });
     106:  }
     107:  function showProcess(isShow, title, msg) {
     108:      if (!isShow) {
     109:          $.messager.progress('close');
     110:          return;
     111:      }
     112:      var win = $.messager.progress({
     113:          title: title,
     114:          msg: msg
     115:      });
     116:  }
     117:   
     
    这篇就写到这里吧。如有不足之处,还望大家补充。累了,就先写到这里了。
  • 相关阅读:
    springboot + ApplicationListener
    spring-boot集成swagger
    Servlet对象生命周期(四)
    MyEclipse 基本使用(三)
    Servlet视频-开发第一个java web(最简单的java web程序)(二)
    java Servlet学习笔记(一)
    java JDBC
    冒泡和选择排序 事例
    c#转 java学习笔记(原创)
    数据存储、进制转换
  • 原文地址:https://www.cnblogs.com/XiaoGer/p/2452198.html
Copyright © 2020-2023  润新知