代码改变世界

后台管理系统中的重点知识大全

2017-04-11 14:56  流浪的诗人  阅读(2388)  评论(0编辑  收藏  举报

您的阅读目录:

一、用js来规范时间格式及计算时间差

  1.1、用js来规范时间格式,如"yyyy-mm-dd hh:MM:ss"的格式来显示时间

/**
* 时间格式转化为"yyyy-mm-dd hh:MM:ss"
**/
var formatDate = function (date, type) {
var year = date.getFullYear();//年
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;//月
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();//日
var hour = 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();//秒
if (type != "") {
   var milliseconds = date.getMilliseconds() < 10 ? "0" + date.getMilliseconds() : date.getMilliseconds(); //毫秒
   var milltime = milliseconds.toString().substring(0, 2);
   return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds + "." + milltime;
} else {
   return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}
}

显示结果为:“2017-01-23 21:02:33“

  1.2、用js来计算时间差

    

    var timeInter = (new Date(endTime).getTime() / 1000 - new Date(startTime).getTime() / 1000).toFixed(2);

    其中endTime ,startTime为时间格式;如new Date(“2017-1-23 10:20:30”)

二、sui框架复选框全选和全不选

     

"checkall"为全选框的class;name=achecks为列表复选框的名称;
$(".checkall").click(function() {
    var checked = "";
    var ischecked = $(this).prop('checked');获取全选复选框的状态。
    $("[name=achecks]").each(function() {
        if (ischecked) {
            checked = "check";
        } else {
            checked = "uncheck";
        }
        $(".checkList").parent('label').checkbox(checked).checkbox(checked);
    });
});

原因是:在jquery1.6版本便对此做出了修改:【checked属性在页面初始化的时候已经初始化好了,不会随着状态的改变而改变。
也就是说如果checkbox在页面加载完毕是选中的,那么返回的永远都是checked(我的一开始就是没选中)如果一开始没被选中,则返回的永远是undefined !】
JQ1.6之后,它将“属性”与“特性”做了区别,属性指的是“name,id”等等,特性指的是“selectedIndex, tagName, nodeName”等等。
可以通过attr方法去获得属性,通过prop方法去获得特性。

  • 1. $("#cb").attr("tagName"); //undefined
  • 2. $("#cb").prop("tagName"); //INPUT

 $("#check_all").change(function(){
  $('.check_children').prop("checked",this.checked);
});

三、模拟用户自动点击onclick事件   

function  autoClick(lastId) {
    // IE
    if (document.all) {
        document.getElementById(lastId).click();
    }
        // 其它浏览器
    else {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(lastId).dispatchEvent(e);
    }
}

四、通过点击获取元素id;

jquery调用方法:
$(function () {
    $("div").on('click', function (e) {
        alert($(this).attr('id'));
    });
});
js原生调用方法:
 window.onload = function(){
     document.onclick = function(e){
         var target = e.target|| e.srcElement;
         if(target.tagName =="div"){
              alert(target.id)
         }
     }
 }

五、jqurey选择器在表格中的应用(选择行,列,单元格等)

     (1)、获取表格tr的id值

  

$("#liquiBankList tr").click(function(){ 
     var id = $(this).attr('id');//这样无法获取到id
});

$("#liquiBankTable").on("click", "#liquiBankList tr", function () {
    var id = $(this).attr('id');
});

  (2)、eq(),gt(),lt()应用于表格行列的选择

 $("#connectorBody tr:eq(0)"):选择等于表格的第一行的数据
 $("#connectorBody tr:gt(0)"):选择大于表格的第一行的数据
 $("#connectorBody tr:lt(3)"):选择小于表格的第四行的数据

    (3)、点击全选按钮,是表格里面的第一列的复选框全部被选中

 $("#" + babyId + " tr td:first-child label").checkbox("check").checkbox("check");

六、 js中switch的另类用法:

switch (id) {
        case "categoryli_1":
        case "categoryli_2":
        case "categoryli_3":
              $("#liquiDataList tr td label.checked").each(function () {
                    noListArr.push($(this).parents("tr").attr("id"));
                });
              if(id == "categoryli_1"){
                 value == 1;
              }else if(id == "categoryli_2"){
                value == 2;
              }
       break;
}

七、.children() ,find(),parent()和parents()的用法

(1)、children() ,find()
相同点:都允许我们检索 DOM 树中的后代元素,并用匹配元素构造新的 jQuery 对象。
不同点:
.children() 只沿着 DOM 树向下遍历单一层级;
.find()可沿着DOM树向下遍历多个层级。

(2)、parent()和parents()
相同点:都允许我们检索 DOM 树中的父辈元素,并用匹配元素构造新的 jQuery 对象。
.parent()方法返回被选元素的直接父元素。
.parents()函数是往父级找多层,一直找到body标签。

八、解决使用setInterval()间隔调用ajax方法,出现结果异步的情况。

function  getName(){
       $.ajax({
             async:false
             type:"post/get"
             ulr:
             contentType:
             data:
             dataType:    
        });
   }
 setInterval("getName()",3000);

当用setInterval进行间隔时间调用方法时,如果被调用的方法里面存在异步,则会导致调用数据不一致。
解决方法:ajax请求默认为异步,当设置为同步调用时即可。增加一个参数设置: async: false。

九、运用localstorage来保存对象数据的方法

var liquiMenuInfo = {
    queryoutname: $(this).parents(".sub-menu").data("name"),
    queryouttext: $(this).parents(".sub-menu").find(".outername").text(),
    queryinnername: $(this).data('name'),
    queryinnertext: $(this).find("span").text()
};
localStorage.setItem("liquiMenuInfo", JSON.stringify(liquiMenuInfo));

function getliquiMenuInfo() {
    return JSON.parse(localStorage.getItem("liquiMenuInfo"));
}

 十、onload,onresize在窗口加载、放大或缩小时,实现页面的自适应

    function changeFrameHeight() {
        var height = document.body.clientHeight;//iframe的高度
        var width = document.body.clientWidth;//为body的宽度
        console.log(height + "," + width);
        $(".wrapperRight").css('width', width - 350 + 'px');
        $(".wrappertop").css('height', height - 120 + 'px');
        $(".wrapperTable").css('height', height - 180 + 'px');
    }
//窗口放大或缩小的时候 window.onresize
= function () { changeFrameHeight(); }
//页面初始化加载的时候 window.onload
= function () { changeFrameHeight(); }

 十一、window.print()实现浏览器打印表格

printDatas为object,传递进来的参数。
 //打印表格
    function printdiv(printDatas) {
        var headstr = "<html><div class='printName'>" + printDatas.printName + "</div><h2 class='printTitle'>" + printDatas.printTitle + "</h2>" + printDatas.printSubtitle + "<body>";
        var footstr = "<div class='printFooter'><ul><li>打印柜员:系统管理员</li><li>打印日期:" + printDatas.printDate + " </li><li>复&nbsp;核:</li></ul> </div></body></html>";
        var newstr = printDatas.printpage;
        var oldstr = document.body.innerHTML;
        document.body.innerHTML = headstr + newstr + footstr;
        window.print();
        document.body.innerHTML = oldstr;
//如果发现打印页面出现后,但不能使用以前的js文件,需要重新去加载一次js
var script = document.createElement("script"); script.src = "../js/reportFormQuery.js"; document.body.appendChild(script); localStorage.setItem("isPrint",true); return false; }

 十二、用jquery来筛选id不等于某值的写法

       $("#WJCJIlist tr:not(#1)").show();意思是排除表格的第一行,全部都显示。

$("#allopen").click(function() {
        var ischeck = $(this)[0].checked;
        if (ischeck) {
            $("#WJCJIlist tr:not(#1)").show();
            //$("#WJCJIlist tr[id!="1"]").show();这种写法提示css3中不支持;
        } else {
            $("#WJCJIlist tr:not(#1)").hide();
           // $('#WJCJIlist tr[id!=1]').hide();
        }
    });

十三、使用sui的modal模态框时,禁用点击确定按钮关闭模态框的行为;

     禁用点击空白处,模态框隐藏,需要添加属性:data-backdrop = "static";
     禁用点击ESC键,模态框隐藏,需要添加属性:data-keyboard = "false";
     即正确的写法为:

 <div id="operateModal" tabindex="-1" role="dialog" data-hasfoot="false" class="sui-modal hide fade" data-backdrop="static" data-keyboard="false">

十四、点击排除自己以外的区域隐藏自己

    如图:在管理系统后台,经常会出现点击用户名旁边的小三角,出现logout下拉的弹框。一般情况下,下拉的弹框下面都会有其他的内容,我们希望实现点击弹框自己以外的区域,弹框能够隐藏。其中$(".namelogout")指的是名称和图像区域,$(".logoutarea")指的是弹框区域,要实现这种效果,代码如下:

 $(".namelogout").click(function (e) {
       e = e || event; stopFunc(e);
        $(".logoutarea").toggle(500);
    });
    $(document).click(function (e) {
        e = e || event; stopFunc(e);
        $(".logoutarea").hide(500);
    });
    //阻止向上传递事件
    $('.logoutarea').bind("click", function (e) {
        e = e || event; stopFunc(e);
    });
    function stopFunc(e) {
        e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
    }

 十五、表格奇偶行,首位列选择及全选功能相关操作

    (1)、获取表格的奇偶行

  css表示法:

奇数行:table tr:nth-child(odd){background-color:#d9edf7;}
偶数行:table tr:nth-child(even){background-color:#d9edf7;}

    jquery表示法:

奇数行:$("#connectorBody tr:odd").addClass('success');
偶数行:$("#connectorBody tr:even").addClass('info');

(2)、获取表格的第一列和最后一列

   css表示法:

第一列:body tr td:first-child{background-color:#d9edf7;}
最后一列:body tr td:last-child{background-color:#d9edf7;}

  jquery表示法:

var length = $("#connectorBody tr").length;
$("#connectorBody tr").each(function(){
    $(this).find("td:eq(0)").addClass('success');//获取表格第一列
    $(this).find("td:eq("+length+")").addClass('info');//获取表格最后一列
})

   效果如图:

  

(3)、获取表格的第一行和最后一行的表示法:

      css表示法:

第一行:body tr:first-child{}  
最后一行:body tr:last-child{}

    jquery表示法:

第一行:$("#"+tbodyId+" tr:eq(0)")].css();
最后一行:
var rownum = $("#liquiDataList tr").length-1;
$("#"+tbodyId+" tr:eq(rownum )")].css();

   (4)、获取表格区间行的表示法

    jquery表示法:

选择第一行和第二行的数据,并给其设置颜色;
 $("#connectorBody tr").each(function(index){
    if(index > 0 && index < 3){
      $(this).css('color','blue');
   }
});

效果如图:

   

 十六、设置某个div区域的滚动条的长宽及样式

/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/

.div ::-webkit-scrollbar {
    width:3px;
    height:0px;
}

/*定义滚动条轨道 内阴影+圆角*/

.div ::-webkit-scrollbar-track {
    background-color:#bee1eb;
}

/*定义滑块 内阴影+圆角*/

.div ::-webkit-scrollbar-thumb {
    background-color:#00aff0;
}

/*鼠标放到滚动条里小方块的外观颜色变化*/

.div ::-webkit-scrollbar-thumb:hover {
    background-color:#9c3;
}

滚动条组成
● ::-webkit-scrollbar 滚动条整体部分
● ::-webkit-scrollbar-thumb 滚动条里面的小方块,能向上向下移动(或往左往右移动,取决于是垂直滚动条还是水平滚动条)
● ::-webkit-scrollbar-track 滚动条的轨道(里面装有Thumb)
● ::-webkit-scrollbar-button 滚动条的轨道的两端按钮,允许通过点击微调小方块的位置。
● ::-webkit-scrollbar-track-piece 内层轨道,滚动条中间部分(除去)
● ::-webkit-scrollbar-corner 边角,即两个滚动条的交汇处
● ::-webkit-resizer 两个滚动条的交汇处上用于通过拖动调整元素大小的小控件

十七、append()和appendTo()的区别:

     append() 和 appendTo() 方法执行的任务相同。不同之处在于:内容的位置和选择器。

(1)、append():在被选元素的结尾(仍然在内部)插入指定内容。

语法:$(selector).append(content)

在每个 p 元素结尾插入内容:

$("button").click(function(){
  $("p").append(" <b>Hello world!</b>");
});

(2)、appendTo():方法在被选元素的结尾(仍然在内部)插入指定内容。

语法:$(content).append(selector)

在每个 p 元素结尾插入内容:

$("button").click(function(){
  $("<b>Hello World!</b>").appendTo("p");
});

prepend()和prependTo()的区别

(1)、prepend() 方法在被选元素的开头(仍位于内部)插入指定内容。

提示:prepend() 和 prependTo() 方法作用相同。差异在于语法:内容和选择器的位置,以及 prependTo() 无法使用函数来插入内容。

语法:$(selector).append(content)

在 p 元素的开头插入内容:

$(".btn1").click(function(){
    $("p").prepend("<b>Hello world!</b>");
});

(2)、prependTo() 方法在被选元素的开头(仍位于内部)插入指定内容。

语法:$(content).prependTo(selector);

在p元素的开头插入内容:

$(".btn1").click(function(){
  $("<b>Hello World!</b>").prependTo("p");
});

after()和insertAfter()的区别:

(1)、after() 方法在被选元素后插入指定的内容。

语法:$(selector).append(content)

在每个 p 元素后插入内容:

$("button").click(function(){
  $("p").after("<p>Hello world!</p>");
});

(2)、insertAfter() 方法在被选元素之后插入 HTML 标记或已有的元素。

注释:如果该方法用于已有元素,这些元素会被从当前位置移走,然后被添加到被选元素之后。

语法:$(content).append(selector)

在每个 p 元素之后插入 span 元素:

$("button").click(function(){
  $("<span>Hello world!</span>").insertAfter("p");
});

before()和insertBefore()的区别:

(1)、before() 方法在被选元素前插入指定的内容。

语法:$(selector).append(content)

在每个 p 元素前插入内容:

$("button").click(function(){
    $("p").before("<p>Hello world!</p>");
});

(2)、insertBefore() 方法在被选元素之前插入 HTML 标记或已有的元素。

注释:如果该方法用于已有元素,这些元素会被从当前位置移走,然后被添加到被选元素之前。

语法:$(content).insertBefore(selector)

在每个 p 元素之前插入 span 元素:

$("button").click(function(){
  $("<span>Hello world!</span>").insertBefore("p");
});

 十八、$.inArray()、$.isArray()、$.each()用法比较

(1)、$.inArray():函数用于在数组中搜索指定的值,并返回其索引值。如果数组中不存在该值,则返回 -1。

//在当前页面内追加换行标签和指定的HTML内容
function w( html ){
    $(document.body).append("<br/>" + html);
}
var arr = [ 10, 25, 3, 0, -3 ];
w( $.inArray( 25, arr ) ); // 1
w( $.inArray( -3, arr ) ); // 4
w( $.inArray( 10, arr ) ); // 0
// 数组中没有99
w( $.inArray( 99, arr ) ); // -1
// 数组中有数字10,但是没有字符串"10"
w( $.inArray( "10", arr ) ); // -1

(2)、函数用于判断指定参数是否是一个数组

jQuery.isArray()函数的返回值为Boolean类型,如果指定的参数是数组,则返回true,否则返回false

//在当前页面内追加换行标签和指定的HTML内容
function w( html ){
    $(document.body).append("<br/>" + html);
}
w( $.isArray( [ 10, 25, 3 ] ) ); // true
w( $.isArray( new Array() ) ); // true
w( $.isArray( null ) ); // false
w( $.isArray( true ) ); // false
w( $.isArray( { } ) ); // false

var obj = { };
obj[0] = 10;
obj[1] = 25;
obj[2] = 3;
obj.length = 3;
// obj是一个类数组对象,但它仍然不是一个真正的数组
w( $.isArray( obj ) ); // false

(3)、$.each():函数用于遍历指定的对象和数组,并以对象的每个属性(或数组的每个成员)作为上下文来遍历执行指定的函数。

所谓的上下文,意即该函数内部的this指针引用了该元素。

语法:jQuery.each( object, callback )

jQuery.each()函数还会根据每次调用函数callback的返回值来决定后续动作。如果返回值为false,则停止循环(相当于普通循环中的break);如果返回其他任何值,均表示继续执行下一个循环。使用jQuery.each()函数迭代对象或数组,jQuery示例代码如下:

// 遍历数组元素
$.each( [1, 2, 3] , function(i, item){
    alert("索引=" + i + "; 元素=" + item);  
} );

// 遍历对象属性
$.each( { name: "张三", age: 18 } , function(property, value){
    alert("属性名=" + property + "; 属性值=" + value);    
} );

jQuery.each()函数同样可以遍历jQuery对象中匹配的元素,以下面这段HTML代码为例:

$.each( $("ul li"), function(index, element){
    // this === element
    $(element).html( "编号" + (index + 1) );  
});

或者另一种写法:

$("ul li").each( function(index){
      $(this).html( "编号" + (index + 1) );  
});

 

十九、设置、读取和删除cookies

var common = new function(){
  //设置cookie
    var setCookie(cname, cvalue, exdays) { 
        var d = new Date(); 
        d.setTime(d.getTime() + (exdays*24*60*60*1000)); 
        var expires = "expires="+d.toUTCString(); 
        document.cookie = name + '=0;expires=' + new Date(0).toUTCString() + "; path=/";
    } 
    //获取cookie
    var getCookie(cname) { 
        var name = cname + "="; 
        var ca = document.cookie.split(';'); 
        for(var i=0; i<ca.length; i++) { 
            var c = ca[i]; 
            while (c.charAt(0)==' ') c = c.substring(1); 
            if (c.indexOf(name) != -1) return c.substring(name.length, c.length); 
        } 
         return ""; 
    } 
    //清除cookie
    var clearCookie(name) { 
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = commonsdk.getCookie(name);
        if (cval != null)
        document.cookie = name + '=0;expires=' + new Date(0).toUTCString() + "; path=/";
    }

}
window.commonsdk = new common();

二十、select下拉列表框相关操作

   20.1、初始化显示“请选择角色”,用户点击选项时,消失。只需要给第一个option添加隐藏属性即可。效果如图:

   

  代码如下:

<select class="form-control m-b" name="role" id="role">
    <option value='' style='display: none'>请选择角色:</option>
    <option value='1'>系统管理员</option>
    <option value='2'>普通管理员</option>
    <option value='3'>财务人员</option>
    <option value='4'>小明</option>
    <option value='5'>行政人员</option>
    <option value='6'>人力资源</option>
</select>

   20.2、设置select的默认选中值,如图选中“财务人员”
  通过select的val()来设置选中值$("#role").val(3);
  通过option的value来设置选中值:$("#role option[value=3]").attr('selected', 'selected');
  通过option的eq()设置选中值: $("#role option").eq(3).attr('selected', 'selected');

   20.3、获取select当前选中项的值:
  $('#role').val();
  $('#role option:selected') .val();

   20.4、获取select当前选中项的文本:
  $("#role").find("option:selected").text();
  $('#role option:selected').text();

   20.5、获取当前选中项的索引值:
  $("#role").get(0).selectedIndex;