03 - JQuery - 04.jQuery 其他方法

jQuery 其他方法

jQuery 拷贝对象

$.extend() 方法

  • $.extend([deep], target, object1, [objectN])
    1.deep:true 为深拷贝,false 为浅拷贝【默认】
    2.target:要拷贝的目标对象
    3.object1:待拷贝到第一个对象的对象
    4.objectN:待拷贝到第N个对象的对象

浅拷贝与深拷贝

  • 浅拷贝:把被拷贝的对象复杂数据类型中的地址拷贝给目标对象,修改目标对象会影响被拷贝对象
  • 深拷贝:deep 为 true,完全克隆(拷贝对象,非地址),修改目标对象不会影响被拷贝对象。
    把数据完全复制一份给目标对象,若有不冲突的属性,合并到一起

示例

<head>
    <script src="jquery.min.js"></script>
    <script>
        $(function() {
            // var targetObj = {};
            // var obj = {
            //     id: 1,
            //     name: "andy"
            // };
            // $.extend(targetObj, obj);
            // console.log(targetObj);  // Object  id: 1, name: "andy"

            // var targetObj = {
            //     id: 0
            // };
            // var obj = {
            //     id: 1,
            //     name: "andy"
            // };
            // $.extend(targetObj, obj);
            // console.log(targetObj);  // Object  id: 1, name: "andy"

            var targetObj = {
                id: 0,
                msg: {
                    sex: '男'
                }
            };
            var obj = {
                id: 1,
                name: "andy",
                msg: {
                    age: 18
                }
            };

            // 浅拷贝
            // $.extend(targetObj, obj);
            // console.log(targetObj);  // Object  id: 1, msg: {age: 18}, name: "andy"
            // console.log(obj);  // Object  id: 1, msg: {age: 18}, name: "andy"
            // targetObj.msg.age = 20;
            // console.log(targetObj);  // Object  id: 1, msg: {age: 20}, name: "andy"
            // console.log(obj);  // Object  id: 1, msg: {age: 20}, name: "andy"

            // 深拷贝
            $.extend(true, targetObj, obj);
            console.log(targetObj);  // id: 1, msg: {sex: '男', age: 18}, name: "andy"
            console.log(obj);  // id: 1, msg: {age: 18}, name: "andy"
            targetObj.msg.age = 20;
            console.log(targetObj);  // id: 0, msg: {sex: '男', age: 20}
            console.log(obj);  // id: 1, msg: {age: 18}, name: "andy"
        })
    </script>
</head>

<body>
</body>

多库共存

存在问题

  • jQuery使用 $ 作为标示符,随 jQuery 流行,其他 js 库也会用其作为标识符,会引起冲突

多库共存

  • jQuery 和其他 js 库不存在冲突,可同时存在

解决方案

  • $ 统一改为 jQuery,如 jQuery("div")
  • jQuery 变量规定新名称 $.noConflict(),释放了对 $ 的控制权,让用户自己决定,如 var xx = $.noConflict()

示例

<head>
    <script src="jquery.min.js"></script>
    <script>
        $(function() {
            function $(ele) {
                return document.querySelector(ele);
            }
            console.log($("div"));

            // $.each();  // 报错,$.each is not a function,与自定义函数冲突
            jQuery.each();  // 法一
            
            var lulu = jQuery.noConflict();  // 法二
            console.log(lulu("span"));
            lulu.each();
        })
    </script>
</head>

<body>
    <div></div>
    <span></span>
</body>

jQuery 插件

jQuery 插件概述

  • 提供更复杂的特效效果
  • 这些插件也是依赖于 jQuery 完成的,故需先引入 jQuery 文件

jQuery 插件常用网站

  • http://www.jq22.com/【jQuery 插件库】
  • http://www.htmleaf.com/【jQuery 之家】

jQuery 插件使用步骤

  1. 引入相关文件【jQuery 文件 和 插件文件】
  2. 复制相关 html、css、js【调用插件】

jQuery 插件示例

  1. 瀑布流插件
    // http://www.htmleaf.com/jQuery/pubuliuchajian/201601093003.html
    // jQuery 之家,兼容 IE8 的响应式网格瀑布流布局 jQuery 插件
    // index.html
    <head>
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" type="text/css" href="css/default.css">
        <style type="text/css">
            #gallery-wrapper {
                position: relative;
                max-width: 75%;
                width: 75%;
                margin: 50px auto;
            }
            img.thumb {
                width: 100%;
                max-width: 100%;
                height: auto;
            }
            .white-panel {
                position: absolute;
                background: white;
                border-radius: 5px;
                box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3);
                padding: 10px;
            }
            .white-panel h1 {
                font-size: 1em;
            }
            .white-panel h1 a {
                color: #A92733;
            }
            .white-panel:hover {
                box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5);
                margin-top: -5px;
                -webkit-transition: all 0.3s ease-in-out;
                -moz-transition: all 0.3s ease-in-out;
                -o-transition: all 0.3s ease-in-out;
                transition: all 0.3s ease-in-out;
            }
        </style>
    </head>
    
    <body>
        <section id="gallery-wrapper">
            <article class="white-panel">
                <img src="images/P_000.jpg" class="thumb">
                <h1><a href="#">我是轮播图片1</a></h1>
                <p>里面很精彩哦</p>
            </article>
            <article class="white-panel">
                <img src="images/P_001.jpg" class="thumb">
                <h1><a href="#">Title 1</a></h1>
                <p>Description 1</p>
            </article>
            <article class="white-panel">
                <img src="images/P_002.jpg" class="thumb">
                <h1><a href="#">Title 1</a></h1>
                <p>Description 1</p>
            </article>
            <article class="white-panel">
                <img src="images/P_003.jpg" class="thumb">
                <h1><a href="#">Title 1</a></h1>
                <p>Description 1</p>
            </article>
            <article class="white-panel">
                <img src="images/P_004.jpg" class="thumb">
                <h1><a href="#">Title 1</a></h1>
                <p>Description 1</p>
            </article>
            <article class="white-panel">
                <img src="images/P_005.jpg" class="thumb">
                <h1><a href="#">我是轮播图片1</a></h1>
                <p>里面很精彩哦</p>
            </article>
            <article class="white-panel">
                <img src="images/P_006.jpg" class="thumb">
                <h1><a href="#">我是轮播图片1</a></h1>
                <p>里面很精彩哦</p>
            </article>
            <article class="white-panel">
                <img src="images/P_007.jpg" class="thumb">
                <h1><a href="#">我是轮播图片1</a></h1>
                <p>里面很精彩哦</p>
            </article>
        </section>
    
        <script src="js/jquery-1.11.0.min.js"></script>
        <script src="js/pinterest_grid.js"></script>
        <script type="text/javascript">
            $(function() {
                $("#gallery-wrapper").pinterest_grid({
                    no_columns: 4,
                    padding_x: 10,
                    padding_y: 10,
                    margin_bottom: 50,
                    single_column_breakpoint: 700
                });
            });
        </script>
    </body>
    
  2. 图片懒加载插件【图片使用延迟加载可提高网页下载速度,减轻服务器负载】【EasyLazyload】
    注1:当页面滑动到可视区域,再显示图片。js 文件和 js 调用必须写到 DOM元素(图片)最后面
    注2:将图片 src 替换为 data-lazy-src
    // https://www.jq22.com/jquery-info11629
    // jQuery 插件库,超好用js图片延迟加载
    // index.html
    <head>
        <meta charset="UTF-8">
        <title>品优购-综合网购首选-正品低价、品质保障、配送及时、轻松购物!</title>
        <meta name="description" content="品优购JD.COM-专业的综合网上购物商城,销售家电、数码通讯、电脑、家居百货、服装服饰、母婴、图书、食品等数万个品牌优质商品.便捷、诚信的服务,为您提供愉悦的网上购物体验!" />
        <meta name="Keywords" content="网上购物,网上商城,手机,笔记本,电脑,MP3,CD,VCD,DV,相机,数码,配件,手表,存储卡,品优购" />
        <!-- 引入facicon.ico网页图标 -->
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
        <!-- 引入css 初始化的css 文件 -->
        <link rel="stylesheet" href="css/base.css">
        <!-- 引入公共样式的css 文件 -->
        <link rel="stylesheet" href="css/common.css">
        <!-- 引入 首页的css文件 -->
        <link rel="stylesheet" href="css/index.css">
        <script src="js/jquery.min.js"></script>
        <script src="js/index.js"></script>
    </head>
    <body>
        <script src="js/EasyLazyload.min.js"></script>
        <script>
            lazyLoadInit({
                showTime: 1100,
                onLoadBackEnd: function(i, e) {
                    console.log("onLoadBackEnd:" + i);
                },
                onLoadBackStart: function(i, e) {
                    console.log("onLoadBackStart:" + i);
                }
            });
        </script>
    </body>
    
  3. 全屏滚动插件(fullpage.js)
    https://github.com/alvarotrigo/fullPage.js【gitHub】
    http://www.dowebok.com/demo/2014/77/【中文翻译网站】
    <head>
        <link rel="stylesheet" href="css/fullpage.min.css">
        <style>
            #fp-nav ul li a.active span,
            #fp-nav ul li a span {
                background-color: red!important;
            }
            .section1 {
                background: url(http://idowebok.u.qiniudn.com/77/1.jpg) 50%;
            }
            .section2 {
                background: url(http://idowebok.u.qiniudn.com/77/2.jpg) 50%;
            }
            .section3 {
                background: url(http://idowebok.u.qiniudn.com/77/3.jpg) 50%;
            }
            .section4 {
                background: url(http://idowebok.u.qiniudn.com/77/4.jpg) 50%;
            }
        </style>
        <script src="js/jquery.min.js"></script>
        <script src="js/fullpage.min.js"></script>
        <script>
            $(function() {
                $('#dowebok').fullpage({
                    sectionsColor: ['pink', '#4BBFC3', '#7BAABE', '#f90'],
                    navigation: true
                });
            });
        </script>
    </head>
    
    <body>
        <div id="dowebok">
            <div class="section section1">
                <h3>第一屏里面的内容</h3>
            </div>
            <div class="section section2">
                <h3>第二屏</h3>
            </div>
            <div class="section section3">
                <h3>第三屏</h3>
            </div>
            <div class="section section4">
                <h3>第四屏</h3>
            </div>
        </div>
    </body>
    
  4. bootstrap JS插件
    bootstrap 框架也是依赖 jQuery 开发的,故里面的 js 插件使用,也必须引入 jQuery 文件
    https://www.bootcss.com/
    // bootstrap 示例
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
        <script src="bootstrap/js/jquery.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
    </head>
    
    <body>
        <div class="container">
    
            <!-- Single button -->
            <div class="btn-group">
                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Action <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">Separated link</a></li>
                </ul>
            </div>
    
            <!-- // 导航条组件 -->
            <nav class="navbar navbar-default">
                <div class="container-fluid">
                    <!-- Brand and toggle get grouped for better mobile display -->
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#">Brand</a>
                    </div>
                    <!-- Collect the nav links, forms, and other content for toggling -->
                    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                        <ul class="nav navbar-nav">
                            <li class="active"><a href="#">首页 <span class="sr-only">(current)</span></a></li>
                            <li><a href="#">公司简介</a></li>
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                                <ul class="dropdown-menu">
                                    <li><a href="#">Action</a></li>
                                    <li><a href="#">Another action</a></li>
                                    <li><a href="#">Something else here</a></li>
                                    <li role="separator" class="divider"></li>
                                    <li><a href="#">Separated link</a></li>
                                    <li role="separator" class="divider"></li>
                                    <li><a href="#">One more separated link</a></li>
                                </ul>
                            </li>
                        </ul>
                        <form class="navbar-form navbar-left">
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Search">
                            </div>
                            <button type="submit" class="btn btn-default">Submit</button>
                        </form>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a href="#">Link</a></li>
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                                <ul class="dropdown-menu">
                                    <li><a href="#">Action</a></li>
                                    <li><a href="#">Another action</a></li>
                                    <li><a href="#">Something else here</a></li>
                                    <li role="separator" class="divider"></li>
                                    <li><a href="#">Separated link</a></li>
                                </ul>
                            </li>
                        </ul>
                    </div>
                    <!-- /.navbar-collapse -->
                </div>
                <!-- /.container-fluid -->
            </nav>
    
            <!-- 模态框 -->
            <!-- Large modal -->
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large modal</button>
            <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        里面就是模态框
                    </div>
                </div>
            </div>
    
            <!-- 自己定义模态框 -->
            <!-- <button data-toggle="modal" data-target="#btn">点击显示模态框</button> --> <!-- 法一 -->
            <button class="myBtn">点击显示模态框</button> <!-- 法二 -->
            <div class="modal fade" tabindex="-1" role="dialog" id="btn">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">Modal title</h4>
                        </div>
                        <div class="modal-body">
                            <p>One fine body&hellip;</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
    
            <!-- // tab栏切换  -->
            <div>
                <!-- Nav tabs -->
                <ul class="nav nav-tabs" role="tablist">
                    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">手机</a></li>
                    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">电视</a></li>
                </ul>
                <!-- Tab panes -->
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="home">手机相关的内容</div>
                    <div role="tabpanel" class="tab-pane" id="profile">电视相关的内容</div>
                </div>
            </div>
        </div>
    
        <script>
            // 点击自定义按钮,弹出模态框 法二
            $(".myBtn").on("click", function() {
                // alert(11);
                $('#btn').modal()
            })
        </script>
    </body>
    

toDoList 示例

JSON.stringify(data) 与 JSON.parse()

  • 本地存储 localStorage 中只能存储字符串格式
  • JSON.stringify(data)【对象转为字符串】
  • JSON.parse(data)【字符串转为对象】
    // 本地存储的数据格式.html
    <head>
        <title>Document</title>
        <script src="js/jquery.min.js"></script>
    </head>
    
    <body>
        <script>
            var todolist = [{
                title: '我今天吃八个馒头',
                done: false
            }, {
                title: '我今天学习jq',
                done: false
            }, ];
    
            // localStorage.setItem("todo", todolist);  // [object Object],[object Object]
            localStorage.setItem("todo", JSON.stringify(todolist));  // [{"title":"我今天吃八个馒头","done":false},{"title":"我今天学习jq","done":false}]
            var data = localStorage.getItem("todo");
            // console.log(typeof data);  // string
            // console.log(data[0].title);  // undefined
    
            data = JSON.parse(data);
            // console.log(data);  // Array
            // console.log(data[0].title);  // 我今天吃八个馒头
        </script>
    </body>
    

jQuery index() 方法何时失效

  • 代码分析
    <head>
        <title>Document</title>
        <script src="js/jquery.min.js"></script>
    </head>
    
    <body>
        <div>
            <a href="#">1</a>
            <a href="#">2</a>
            <a href="#">3</a>
        </div>
        <ul>
            <li><a href="#">a</a></li>
            <li><a href="#">b</a></li>
            <li><a href="#">c</a></li>
        </ul>
        <script>
            $("div a").click(function() {
                console.log($(this).index());  // 亲兄弟 0 1 2
            })
            $("ul a").click(function() {
                console.log($(this).index());  // 表兄弟 0 0 0
            })
        </script>
    </body>
    

删除某特定元素

  • 代码分析
    <head>
        <title>Document</title>
    </head>
    
    <body>
        <script>
            var arr = ['a', 'b', 'c'];
            arr.splice(1, 1);  // splice(从哪个位置开始删除, 删除几个元素)
            console.log(arr);  // a c
        </script>
    </body>
    

toDoList 示例

  • 代码
    // todolist.html
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <title>ToDoList—最简单的待办事项列表</title>
        <link rel="stylesheet" href="css/index.css">
        <script src="js/jquery.min.js"></script>
        <script src="js/todolist.js"></script>
    </head>
    
    <body>
        <header>
            <section>
                <label for="title">ToDoList</label>
                <input type="text" id="title" name="title" placeholder="添加ToDo" required="required" autocomplete="off" />
            </section>
        </header>
        <section>
            <h2>正在进行 <span id="todocount"></span></h2>
            <ol id="todolist" class="demo-box">
            </ol>
            <h2>已经完成 <span id="donecount"></span></h2>
            <ul id="donelist">
            </ul>
        </section>
        <footer>
            Copyright &copy; 2014 todolist.cn
        </footer>
    </body>
    
    // todolist.js
    $(function () {
        load();  // 预加载
        // 监听键盘事件
        $("#title").on("keydown", function(event) {
            if (event.keyCode === 13) {
                if ($(this).val() === "") {
                    alert("请输入您要的操作");
                } else {
                    var local = getData();
                    local.push({title: $(this).val(), done: false});
                    saveData(local);
                    load();
                    $(this).val("");
                }
            }
        });
    
        // 删除操作
        $("ol, ul").on("click", "a", function() {
            var data = getData();
            var index = $(this).attr("id");
            data.splice(index, 1);
            saveData(data);
            load();
        });
    
        // 待办及已完成事件
        $("ol, ul").on("click", "input", function() {
            var data = getData();
            var index = $(this).siblings("a").attr("id");
            data[index].done = $(this).prop("checked");
            console.log(data);
            saveData(data);
            load();
        });
    
        function getData() {
            var data = localStorage.getItem("todolist");
            return data ? JSON.parse(data) : [];
        }
    
        function saveData(data) {
            localStorage.setItem("todolist", JSON.stringify(data));
        }
    
        function load() {
            var data = getData();
            $("ol, ul").empty();
            var todoCount = 0;
            var doneCount = 0;
            $.each(data, function(i, n) {
                if (n.done) {
                    $("ul").prepend("<li> <input type='checkbox' checked='checked'> <p>" + n.title + "</p> <a href='javascript:;' id=" + i + "></a> </li>");
                    doneCount++;
                } else {
                    $("ol").prepend("<li> <input type='checkbox' > <p>" + n.title + "</p> <a href='javascript:;' id=" + i + "></a> </li>");
                    todoCount++;
                }
            });
            $("#todocount").text(todoCount);
            $("#donecount").text(doneCount);
        }
    });
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值