【知识碎片】JavaScript篇

 40、选择器组合

逗号是多选择器
空格 是子子孙孙
尖括号 只找儿子

39、失去焦点事件blur

$("input").blur(function(){
  $("input").css("background-color","#D6D6FF");
});

38、图片延迟加载

Lozad.js  

jQuery.lazyload

demo:https://apoorv.pro/lozad.js/demo/

37、纯JS复制文本到检测板  

clipboard.js

官网:https://clipboardjs.com/

GIT:https://github.com/zenorocha/clipboard.js/archive/master.zip

36、二维码JS库

https://github.com/xiaoshi657/qrcodejs

<div id="qrcode"></div>
<script type="text/javascript">
new QRCode(document.getElementById("qrcode"), "http://jindo.dev.naver.com/collie");
</script>

35、jquery中ifram子窗体调用父窗体方法、父窗体调用子窗体方法

//调用子窗体中的方法.
 var childWindow = $("#AddFrame")[0].contentWindow;//获取子窗体的window对象


 childWindow.subForm();
 //调用父窗体中的方法
  window.parent.afterAdd();

34、省市联动 遍历json数组

 //地址改变事件
    $("#ProvinceCode").change(function (e) {
        $.ajax({
            type: "POST",
            url: "/usercenter/uaccount/getcitylist",
            data: {provinceCode:$("#ProvinceCode").val()},
            success: function (result) {
                //result :[{"ID":127,"Code":"360100","Name":"南昌市","ProvinceCode":"360000"},{"ID":128,"Code":"360200","Name":"景德镇市","ProvinceCode":"360000"}]
                var tempHtml="";
                for (var i in result) {
                    tempHtml+='<option value="'+result[i].Code+'">'+result[i].Name+'</option>';
                }
                $("#CityCode").html(tempHtml);
            },
            dataTypeString: "json"
        });
View Code

c#代码:

  public ActionResult GetCityList(string provinceCode)
        {
            List<S_City> cityList = CacheHelper.GetCache("CityCache") as List<S_City>;
            if (cityList == null)
            {
                XS.EasyBlog.BLL.S_CityService citybll = new BLL.S_CityService();
                cityList = citybll.LoadEntities(c => true).ToList();
                CacheHelper.SetCache("CityCache", cityList);
            }

            cityList = cityList.Where(c => c.ProvinceCode == provinceCode).ToList();
            //ViewBag.CityList = cityList;
            return Json(cityList, JsonRequestBehavior.AllowGet);
            //return View(CurrentMember);
        }
View Code

33、获取form表单所有值

    $("#commitInfoForm").click(function () {
        alert($("#accountInfoForm").serialize());//.serializeArray();
    });

键值对:

$("button").click(function(){
  x=$("form").serializeArray();
  $.each(x, function(i, field){
    $("#results").append(field.name + ":" + field.value + " ");
  });
});

32、json转换

var obj = eval('(' + str + ')');
var last=JSON.stringify(obj); //将JSON对象转化为string字符

31、IE8屏蔽错误

重写方法

    window.onerror = function () { return true; }
    console.log = function () { };
    console.error = function () { };
<script>
    window.console = window.console || (function () {
        var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
        = c.clear = c.exception = c.trace = c.assert = function () { };
        return c;
    })();
</script>

30、jqzoom.js 图片放大器

SWFUpload 文件上传

29、数组中存在则移除

AddMemberIDList.splice($.inArray(MemberID, AddMemberIDList), 1);
//1:移除的次数这里指一次  0:不移除  

28、可以关闭的小广告

var dvObj = $('<div style="300px; height:200px;position:absolute;right:0;bottom:0;"></div>').appendTo($('body')); //层来了

                //可以关闭广告

                $('<span style="float:right; cursor:pointer;">×</span>').click(function () {
                    $(this).parent().remove();

                }).appendTo(dvObj);

27、请仔细阅读协议

        $(function () {

            var sec = 5;
            var setId = setInterval(function () {
                sec--;
                if (sec <= 0) {
                    sec = 0;
                    clearInterval(setId);
                    $('#btn').val('同意').attr('disabled',false);
                } else {
                    $('#btn').val('请仔细阅读协议(' + sec + ')');
                }
            }, 1000);
        });
    

26、jq的cookie处理 jquery.cookie.js

1、引用  jquery.cookie.js

2、用下面这段代码   两个方式都很好用

//写cookies
function setCookie(name, value,time) {
    var Days = time||365;
    var exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString()+";path=/;";
}
//读取cookies
function getCookie(sName) {
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    return null;
}

//删除cookies
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() + -1 * 24 * 60 * 60 * 1000);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=;expires=" + exp.toGMTString() + "; path=/;";
}
//清楚所有cookie
function clareCookie() {

    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; "); // 将多cookie切割为多个名/值对
    for (var i = 0; i < arrCookie.length; i++) { // 遍历cookie数组,处理每个cookie对
        var arr = arrCookie[i].split("=");
        if (arr.length > 0)
            delCookie(arr[0]);
    }
}
View Code
//创建一个超链接添加到body中

                 $('<a href="http://www.baidu.com"></a>').text('百度').appendTo($('body'));

                //在body中添加超链接
               // var akObj = $('<a href="http://www.baidu.com"></a>').text('百度');
               // $('body').append(akObj);
              //表示的是包含哈哈这两个字的内容的层
                //$('div:contains(哈哈)').css('fontSize','100px');
                //空层
                //$('div:empty').css('backgroundColor', 'pink');
                //所有DIV中包含a标签的div北京为蓝色
                $('div:has(a)').css('backgroundColor', 'pink');

25、循环遍历checkbox /radio

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.8.3.js" type="text/javascript"></script>
    <script type="text/javascript">


        $(function () {


            $('#btn').click(function () {
                var cks = $('div input:checked');

                //元素的each用法
                cks.each(function (index, ele) {
                    alert($(ele).val());
                });
            });

        });
    
    </script>
</head>
<body>
    <input type="button" name="name" value="显示value值" id="btn" />
    <div id="dv">

        <input type="checkbox" name="name" value="1" />吃饭
        <input type="checkbox" name="name" value="2" />睡觉
        <input type="checkbox" name="name" value="3" />打豆豆
        <input type="checkbox" name="name" value="4" />打篮球
        <input type="checkbox" name="name" value="5" />打足球
        <input type="checkbox" name="name" value="6" />打铅球
    </div>
</body>
</html>
View Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.8.3.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () {
            //全选
            $('#btnAll').click(function () {

                $('div :checkbox').attr('checked', true);
            });
            //全不选
            $('#btnNoAll').click(function () {

                $('div :checkbox').attr('checked', false);
            });
            //反选
            $('#btnFX').click(function () {

                $('div :checkbox').each(function (index, ele) {
                    $(ele).attr('checked', !$(ele).attr('checked'));
                });
            });
        });

    
    </script>
</head>
<body>
    <input type="button" name="name" value="全选" id="btnAll" />
    <input type="button" name="name" value="全不选" id="btnNoAll" />
    <input type="button" name="name" value="反选" id="btnFX" />
    <div style="border: 1px solid red; height: 200px;">
        <input type="checkbox" name="name" value="1" />忐忑
        <input type="checkbox" name="name" value="2" />法海不懂爱
        <input type="checkbox" name="name" value="3" />金箍棒
        <input type="checkbox" name="name" value="4" />爱情买卖
        <input type="checkbox" name="name" value="5" />最炫民族风
    </div>
</body>
</html>
View Code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <input type="button" value="全选" onclick="checkAll();" />
    <input type="button" value="反选" onclick="reverseAll();" />
    <input type="button" value="取消"  onclick="cancleAll();"/>

    <table border="1">
        <thead>
            <tr>
                <th>选项</th>
                <th>IP</th>
                <th>PORT</th>
            </tr>
        </thead>
        <tbody id="tb">

            <tr>
                <td><input type="checkbox" /></td>
                <td>1.1.1.1</td>
                <td>80</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td>1.1.1.1</td>
                <td>80</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td>1.1.1.1</td>
                <td>80</td>
            </tr>
        </tbody>
    </table>

    <script src="jquery-1.12.4.js"></script>
    <script>
        function checkAll() {
            $('#tb :checkbox').prop('checked',true);
        }
        function cancleAll() {
            $('#tb :checkbox').prop('checked',false);
        }
        function reverseAll() {
            $(':checkbox').each(function(k){
                // this,代指当前循环的每一个元素
                // Dom
                /*
                if(this.checked){
                    this.checked = false;
                }else{
                    this.checked = true;
                }
                */
                /*
                if($(this).prop('checked')){
                    $(this).prop('checked', false);
                }else{
                    $(this).prop('checked', true);
                }
                */
              // 三元运算var v = 条件? 真值:假值
               // var v = $(this).prop('checked');//?false:true;
                $(this).prop('checked',!$(this).prop('checked'));
            })
        }
    </script>
</body>
</html>
View Code

24、获取被选中的checked  input

$('input:checked').css('backgroundColor', 'red');//获取 被选中的元素
<div>
     <input type="checkbox" name="name" value="1" checked="checked" />吃饭
     <input type="checkbox" name="name" value="2"  checked="checked" />睡觉
     <input type="checkbox" name="name" value="3" />打豆豆
    </div>
   

23、两个加载的区别onload

onload $(document).ready(function (){}) 区别

前者是图片类资源都加载完执行

或者是基本标签加载完执行

前者只可以写一个,多写后面的会覆盖前面的,后者写多少个执行多少个

后者的终极写法

$(function (){})
$(document).ready(function (){})
//
$(function (){})
//功能一样都是加载完执行

22、JS正则

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
//返回true 
//RegExp 对象有 3 个方法:test()、exec() 以及 compile()//返回bool、返回匹配到的字符
var msg= "      去掉空格      " 

msg = msg.replace(/^s+/g, '');// s空格

正则表达式中/i,/g,/ig,/gi,/m的区别和含义

/i (忽略大小写)
/g (全文查找出现的所有匹配字符)
/m (多行查找)
/gi(全文查找、忽略大小写)
/ig(全文查找、忽略大小写)

21、js 随机数 整数

$(document).ready(function() {    

   //x上限,y下限    

       var x = 12;       

     var y = 0;           

   var rand = parseInt(Math.random() * (x - y + 1) + y);      

        $("#b").html("").append("<div>" + rand + "</div>");    

 

      })    

 从1开始 至 任意值    

 

parseInt(Math.random()*上限+1);   

 

2. 从任意值开始 至 任意值  

 

parseInt(Math.random()*(上限-下限+1)+下限);   

 

random是0到1之间(不包括1)的伪随机函数,floor是取当前数值的整数部分值,舍掉小数部分.

常搭配使用,用来取0到某个数值之间的随机数.如想取0~49之间的随机数可用:

Math.floor(Math.random()*50),最大值再大也不到50,后舍掉小数部分就是0~49的任意一个伪随机数.

round是取近似值的数,也就是四舍五入的说法.返回一个整数值,配合使用如:

Math.round(Math.atan2(y,x))来返回一个角度的近似整数值

20、判断是否为空

**判断是否null
*@param data
*/
function isNull(data) {
    return (data == "" || data == undefined || data == null);
}

var companyid = new URL().get('CompanyID');
if (companyid != null || companyid != "" || companyid != undefined) {

 

19、去掉最后逗号

chk_id = chk_id.substr(0, chk_id.length - 1);//去掉最后“,”

18、去掉html

                        $("#" + id).parent().parent().remove();

17、setInterval(循环) setTimeout(一次)定时执行

//--------监测UUID  start-------
    //每0.1秒检查一次字符串前34个字符是否等于tvalue如果不等于就重新赋值,
    var tValue = "4F9863FE-96DA-4AB0-AA31-6FE7475A60";
   var intv setInterval(function (event) {
        var value = document.getElementById("UUID").value;
        var val_34 = value.substr(0, 34);//获取前34位
        //var val_2 = value.subStr(value.length - 2, 2);//获取后两位
        if (val_34 != tValue) {
            document.getElementById("UUID").value = $("#hidUUID").val();
        }
    }, 100);
    //---------监测UUID   end--------
//window.clearInterval(intv) //移除


16、setTimeout

setTimeout("alert('5 seconds!')",5000)

15、判断数组中是否存在指定元素

                        //if (MemberIDList.indexOf(_model.FriendID) >= 0) {
                        //    _model.Display = "display:none";
                        //};
                        if ($.inArray(_model.FriendID, MemberIDList)>=0) {
                            _model.Display = "display:none";
                        };

14、checkeBox 限制单选

//$("#myCheckBox").bind('change',function(){});  

//$("#myCheckBox").change(function(){})

//限制单选
    $("input[name='kt']:checkbox").live("click", function () {
        //$("input[name='kt']").each(function () {
        //    $(this).attr('checked', false);
        //});
        //$(this).attr('checked', true);

        if ($(this).is(':checked')) {
            //alert($(this).attr('checked'))
            $(this).attr('checked', true).parent().parent().siblings().children().children().attr('checked', false);
        } else {
            $(this).attr('checked', false).parent().parent().siblings().children().children().attr('checked', false);
        }
    })
View Code

 相关HTML

<!-- 课题选择列表  start-->
    <script id="temp_CompetitionTopicList" type="text/template">
        <li>
            <div class="kt_title"><input class="check_input" name="kt" id="{kt}" type="checkbox" value="{ID}" /><h4>{Num}. {TopicName}<i></i></h4></div>
            <div class="kt_info">{TopicDesc}</div>
        </li>
    </script>
    <!-- 课题选择列表  end-->
View Code

 

原文地址:https://www.cnblogs.com/xiaoshi657/p/4834966.html