jQuery

JavaScript和jquery的对比

书写繁琐,代码量大
代码复杂
动画效果,很难实现。使用定时器 各种操作和处理
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
     div{
      width: 100%;height: 100px;background-color: pink;margin-top: 30px;display: none;}   /*display:none设置元素不会被显示*/
    </style>

</head>
<body>
    <button id="btn">按钮</button>
    <div></div>
    <div></div>
    <div></div>
</body>
<script src="jquery-3.2.1.js"></script>
<script type="text/javascript">
    // window.onload = function(){
    //     document.getElementById('btn').onclick = function(){
    //         var divs = document.getElementsByTagName('div');
    //         for(var i = 0;i<divs.length;i++){
    //             divs[i].style.display = 'block';
    //             divs[i].innerHTML = '我出来了!!'}
    //     }
    // }
    //如果使用jQuery操作上面的案例,很简单,三句代码搞定
    $('#btn').click(function(){
        $('div').css('display','block');
        $('div').html('我出来了')
    })
</script>
</html>

JavaScript和jquery的区别

  1. Javascript是一门编程语言,我们用它来编写客户端浏览器脚本。
  2. jQuery是javascript的一个库,包含多个可重用的函数,用来辅助我们简化javascript开发
  3. jQuery能做的javascipt都能做到,而javascript能做的事情,jQuery不一定能做到

 

注意:一般情况下,是库的文件,该库中都会抛出来构造函数或者对象,如果是构造函数,那么使用new关键字创建对象,如果是对象直接调用属性和方法

DOM文档加载的步骤

1.解析HTML结构。
2.加载外部脚本和样式表文件。
3.解析并执行脚本代码。
4.DOM树构建完成。
5.加载图片等外部文件。
6.页面加载完毕。
执行时间不同

window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行。

$(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕。

编写个数不同

window.onload不能同时编写多个,如果有多个window.onload方法,只会执行一个

$(document).ready()可以同时编写多个,并且都可以得到执行

简化写法不同

window.onload没有简化写法

$(document).ready(function(){})可以简写成$(function(){});

第一个jequry demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box"></div>
    <!--1.引包-->
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        console.log(jQuery);
        console.log($);
        console.log($('.box'));
    </script>
</body>
</html>

入口函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--window.onload()函数有 1.覆盖现象 2.等待图片资源加载完毕之后才能调用脚本代码,用户体验不好这两个问题-->
    <!--jequery框架封装的时候,模仿了伪数组对象,有索引和length属性+n个fn-->
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // 入口函数
        // jquery对象
        $(document)
        // jQuery对象 ===> js 对象的转换
        console.log($(document)[0]);

        // 等待文档资源加载完成后,调用此方法
        $(document).ready(function () {
            alert(1);
        })
        // 上面方法的简便写法,没有覆盖现象
        $(function () {
            alert(2);
        });

        $(window).ready(function () {
            // 表示图片资源加载完成后调用
            console.log(3)
        });
                $(window).ready(function () {
            // 表示图片资源加载完成后调用
            console.log(4)
        })
    </script>
</body>
</html>

jQuery对象和JS对象的转换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #box2{
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <div id="box2"></div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // 入口函数
        $(function () {
           // 获取JQuery对象
           console.log($('#box2'));
           // 获取JS对象
           var oDiv2 = document.getElementById('box2');
           console.log(oDiv2);

           // jQuery ==> JS对象
           console.log($('#box2')[0]);
           console.log($('#box2').get(0));

           // JS对象 ==> jQuery对象
           console.log($(oDiv2));

           // 如果是JS对象,更加希望转换成JQ对象来操作简便的DOM,因为JS包含了JQ的,JQ只是封装了JS中的一部分,如果
            // 需要操作其他的,类如BOM,就需要将JQ对象转换成JS对象
            // 总结:如果是jQuery对象,就一定要调用jQuery的属性和方法
            //       如果是js对象,就一定要调用js的属性和方法,千万不要将这两个对象混淆
            //       在jQuery中,大部分都是api(方法),只有length和索引是属性

        });
    </script>
</body>
</html>

jQuery如何操作DOM

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div{
            margin-top: 10px;
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="box">wusir</div>
    <div id="box">日天</div>
    <div>alex</div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $(function () {

            /* 事件分三部分:
                            1.事件源
                            2.事件
                            3.事件驱动程序
            */

            // jQuery如何获取DOM
            //     1.jQuery的标签选择器
            console.log($('div'));
        })
        // jQuery内部自己遍历
        $('div').click(function () {
            // this是js对象,用js方法获取div内容
            console.log(this.innerText);
            // JQ方法
            console.log($(this).text());
            alert($(this).text());
            $(this).hide(300);
        });
            //      2.类选择器
            console.log($('.box'));
            //      3.id选择器
            console.log($('#box'));
    </script>
</body>
</html>

层级选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul class="lists">
        <li>女友
            <ol>
                <li>alex</li>
            </ol>
        </li>
        <li class="item">
            <a href="#">alex1</a>
        </li>
        <li class="item2">alex2</li>
        <li>alex3</li>
        <li>alex4</li>
        <li>alex5</li>
        <li>alex6</li>
    </ul>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $(function () {
          // 后代选择器
            $('.lists li');
            $('.lists li').css('color', 'yellowgreen');
            // 子代选择器    选中的是亲儿子
            $('.lists>a').css({
                'color':'yellow',
                'font-size':'20px',
                'background':'red'
            })
            // +紧邻选择器
            $('.item+li').css('color','pink');
            // ~所有兄弟选择器
            $('.item2~li').css('color','#666');
        });
    </script>
</body>
</html>

基本过滤选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
    </ul>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        
        $(function () {
            // eq写法('ul li:eq(0)')
            // 1.eq(index)选择序号为index的元素
            $('ul li:eq(1)').css('color','red');
            // 2.gt(index)大于index的元素
            $('ul li:gt(2)').css('color','pink');
            // 3.lt(index)小于
            $('ul li:lt(3)').css('color','green');
            // 4.odd选取的是基数
            $('ul li:odd').css('color','red');
            // 5.even偶数
            $('ul li:even').css('background-color','yellowgreen');
            // 6.选取首尾
            $('ul li:first').css('color','yellow');
            $('ul li:last').css('color','blue');
        })
        
    </script>
</body>
</html>

属性选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="">
        <input type="text" name="">
        <input type="password" name="">
    </form>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $('input[type=text]').css('background','red');
            $('input[type=password]').css('background','pink');
        })
    </script>
</body>
</html>

筛选选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box">
        <p>
            <a href="#">alex</a>
        </p>
        <p>
            <span class="span1">alex1</span>
        </p>
        <p>alex2</p>
        <p class="item3">alex3</p>
        <p>
            <span class="child">alex4</span>
        </p>
        <p>alex5</p>
        <p>alex6</p>
        <div class="child">
            哈哈
        </div>
    </div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // find查找后代,包括子子孙孙
            $('.box').find('p').css('color','red');
            $('.box').find('.item3').css('color','pink');
            $('.box').find('p>.span1').css('color','green');
            // 这种书写方式,在jQuery中叫链式编程,因为有这种书写方式,所以jQuery代码少
            $('.box').find('p>.span1').css('color','green').click(function () {
                alert($(this).text())
            });

            // children子代,获取的是亲儿子
            $('.box').children('.child').css('color','yellowgreen');

            // parent

            // eq(index)
            $('.box p').eq(3).css('background-color','#666');
        })
    </script>
</body>
</html>

siblings选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        button{
            width: 100px;
            height: 50px;
        }
    </style>
</head>
<body>
    <button>按钮1</button>
    <button>按钮2</button>
    <button>按钮3</button>
    <button>按钮4</button>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $('button').click(function () {
                $(this).css('background','yellowgreen').siblings('button').css('background-color','transparent');
            })
        })
    </script>
</body>
</html>

选项卡深入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        ul{
            width: 400px;
            height: 100px;
            overflow: hidden;
        }
        ul li{
            width: 80px;
            height: 100px;
            float: left;
            line-height: 100px;
            text-align: center;
            list-style: none;
            background-color: red;
            margin-left: 10px;
        }
        ul li a{
            display: inline-block;
            color: #fff;
        }
        p{
            display: none;
        }
        p.active{
            display: block;
        }
    </style>
</head>
<body>
    <ul>
        <li>
            <a href="javascript:viod(0)">
                alex1
            </a>
        </li>
        <li>
            <a href="javascript:viod(0)">
                alex2
            </a>
        </li>
        <li>
            <a href="javascript:viod(0)">
                alex3
            </a>
        </li>
        <li>
            <a href="javascript:viod(0)">
                alex4
            </a>
        </li>
    </ul>
    <p class="active">alex1</p>
    <p>alex2</p>
    <p>alex3</p>
    <p>alex4</p>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $('ul li a').click(function () {
                // 写法1
                // $(this).css('background-color','green').parent('li').siblings('li').children('a').css('background-color','transparent');
                // 写法2 选项卡完整版
                $(this).css('background-color','green').parent('li').siblings('li').find('a').css('background-color','transparent');

                // 想获取到dom的索引,通过index()方法获取,注意:要找的是这个元素的兄弟元素的索引值
                var i =$(this).parent('li').index();
                // addClass() removeClass()
                $('p').eq(i).addClass('active').siblings('p').removeClass('active');
            })
        })
    </script>
</body>
</html>

基本动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .box{
            width: 200px;
            height: 200px;
            background-color: red;
            display: none;
        }
    </style>
</head>
<body>
    <button id="show">显示</button>
    <button id="hide">隐藏</button>
    <button id="toggle">开关式动画</button>

    <div class="box"></div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 显示动画
            $('#show').click(function () {
                // 如果是一个按钮控制div显示隐藏,那么需要去控制isShow变量

                // show(动画时间,回调函数)
                // 默认的是normal 400ms slow 600ms fast 200ms
                $('.box').show('slow',function () {
                    $(this).text('alex').css({'line-height':'200px','text-align':'center'});
                });
                
            });
            // 隐藏动画
            $('#hide').click(function () {
                $('.box').hide();
            });
            // 开关式显示隐藏动画
            $('#toggle').click(function () {
                // 操作动画和操作定时器一样,需要先停止再启动
                $('.box').stop().toggle('2000');
            })
        })
    </script>
</body>
</html>

滑入滑出动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .box{
            width: 200px;
            height: 200px;
            background-color: red;
            display: none;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <button id="slideDown">卷帘门下拉</button>
    <button id="slideUp">卷帘门上拉</button>
    <button id="slideToggle">开关式卷帘门</button>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $(function () {
            // 显示滑入
            $('#slideDown').click(function () {
                $('.box').slideDown(300,function () {
                    $(this).text('下来了').css({'line-height':'200px','text-align':'center'});
                });
            });
            // 滑出
            $('#slideUp').click(function () {
                $('.box').slideUp(300,function () {
                    alert('上去了');
                });
            })
            // 开关式
            $('#slideToggle').click(function () {
                $('.box').stop().slideToggle(300);
            })
        });

    </script>

</body>
</html>

淡入淡出的动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .box{
            width: 200px;
            height: 200px;
            display: none;
            background-color: red;
        }
    </style>
</head>
<body>
    <button id="fadeIn">淡入</button>
    <button id="fadeOut">淡出</button>
    <button id="fadeToggle">开关式淡入淡出</button>
    <div class="box"></div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 淡入
            $('#fadeIn').click(function () {
                $('.box').fadeIn(1000);
            });
            // 淡出
            $('#fadeOut').click(function () {
                $('.box').fadeOut(500);
            })
            // 开关式淡入淡出
            $('#fadeToggle').click(function () {
                $('.box').stop().fadeToggle(500);
            })
        })
    </script>
</body>
</html>

自定义动画

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
        div{
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            bottom: 0px;
            left: 0px;
        }
    </style>
</head>
<body>
    <button>播放动画</button>
    <div></div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // animate(队列属性,时间,fn回调函数)
            $('button').click(function () {
                var json = {
                    width: '300',
                    height: '300',
                    top: '300',
                    left: '500',
                    'border-radius': 200

            };
                var json2 = {
                    width: 0,
                    height: 0,
                    top: 10,
                    left: 1000
                };
               $('div').stop().animate(json, 2000,function () {
                   $('div').stop().animate(json2,1000);
               });
            });
        })
    </script>
</body>
</html>

jQuery标签属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        div{
            width: 100px;
            height: 100px;
            background-color: #666;
        }
    </style>
</head>
<body>
    <div title="alex"></div>
    <a href="">百度</a>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        /*总结一下
            1.样式操作css
                css('color')来获取单个值
                css('color':'red')来设置单个值
                css({
                    'key1':'value1',
                    'key2':'value2',
                    })  这里面的key可以是驼峰,也可以是margin-top这种属性值,但属性值要加引号

            2.标签的属性操作
                attr(key)获取单个值
                attr('key','value')设置单个值
                attr({'key1':'value1','key2':'value2'})设置多个值

            3.DOM对象属性操作

            4.类样式属性操作
                addClass() removeClass() toggleClass()

            5.对值的操作
                text() html() val()
                innerText   innerHtml   value
            6.DOM的增删改查
        */
        // js中setAttribute(key,value)设置,getAttribute(key,value)获取,removeAttribute来删除
        $(function () {
            // jq中.attr('')来获取
            console.log($('div').attr('title'));
            //attr(key,value)来设置
            $('div').attr('id','name');
            // 不要通过此方法来设置class值
            // $('div').attr('class','box1')这样设置会有问题,如果想设置,用classname()等方法

            $('a').attr({
                'href':'http://www.baidu.com',
                'title':'度娘知道'
            })
            // 移除
            $('a').removeAttr('title');
        })

    </script>
</body>
</html>

jQuery对DOM的对象属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="radio" name="sex" checked><input type="radio" name="sex"><script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // prop() removeProp()
        $(function () {
            // 获取值,返回布尔值
            console.log($('input[type=radio]').eq(0).prop('checked'));

            $('input[type=radio]').eq(0).prop('aaaa','1111');
            console.log($('input[type=radio]').eq(0));
            $('input[type=radio]').eq(0).removeProp('aaaa');
            console.log($('input[type=radio]').eq(0));
        })
    </script>
</body>
</html>

对类样式的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .box{
            width: 100px;
            height: 100px;
            background-color: red;
        }
        .hidden{
            display: none;
        }
    </style>
</head>
<body>
    <button id="btn">隐藏</button>
    <div class="box"></div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            var isShow = true;
            $('#btn').click(function () {
            /* 1.通过控制类样式属性对盒子进行隐藏
                if (isShow){
                    $('.box').css('display','none');
                    $(this).text('显示');
                    isShow = false;
                }else{
                    $('.box').css('display','block');
                    isShow = true;
                }*/
            // 2. 通过控制类名来显示隐藏 addClass() removeClass()
                if (isShow){
                    $('.box').addClass('hidden');
                    $(this).text('显示');
                    isShow = false;
                }else{
                    $('.box').removeClass('hidden');
                    $(this).text('隐藏');
                    isShow = true;
                }


            });

        })
    </script>
</body>
</html>

jQuery对值的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p id="box">
        wusir
    </p>
    <div class="box">
        女朋友
        <span>alex</span>
    </div>
    <input type="text" value="123">
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 获取文本内容,相当于js中的innerText

            // 获取文本内容,trim()去除前后空格
            console.log($('#box').text().trim());

            // 设置文本内容
            $('#box').text('武sir 男朋友');

            // 获取标签和文本的内容 innerHtml
            console.log($('.box').html().trim());
            // 设置标签和文本内容
            $('.box').html('<h1>Alex</h1>');

            // val()取值 相当于value()
            // 获取
            console.log($('input').val());
            // 赋值
            $('input').val('哎呦我勒个去');
        });
    </script>
</body>
</html>

DOM的父子之间插入1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="wusir">wusir</div>
    <div class="box"></div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        
        $(function () {

            var oP = document.createElement('p');
            oP.innerText = '男朋友';

            // 1.父子之间插入 父元素.append(子) 子元素.appendTo(父)
            // 子元素可以是字符串string,jsDOM对象,或者jq对象
            $('.box').append('哈哈哈');    //普通文本
            $('.box').append('<h2>alex</h2>')  //插入标签+文本
            $('.box').append(oP);   //插入jsDom对象
            $('.box').append($('.wusir'));  //插入jq对象,这个插入操作相当于移动操作


            // 2.appendTo()
            $('<p>日天</p>').appendTo('.box');
            $('<p>日天</p>').appendTo(oP);

            // 这就叫链式编程,简化了代码
            $('<p>日天昊</p>').appendTo(oP).click(function () {
                $(this).css({
                    'width': 100,
                    'color': 'pink',
                    'font-size': 20
                }).text('哎呦喂')
            });
        })
        
    </script>
</body>
</html>

DOM的父子之间插入2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <ul>
        <li>alex</li>
    </ul>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $(function () {
            // 父元素.prepend(子)   子元素.prependTo(父)
            // prepend()插入
            $('ul').prepend('<li>wusir</li>');
            // prependTo()
            $('<li>egon</li>').prependTo('ul');
            $('<li>村长</li>').prependTo('ul').click(function () {
                alert(this.innerText);
            })
        })

    </script>

</body>
</html>

DOM的兄弟之间插入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li class="item">alex</li>

    </ul>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $('.item').after('<li><a href="http://www.baidu.com" class="du">度娘知道</a></li>');

            // 直接使用代码而不修改格式并不报错,使用1前面的撇号代替引号,想直接插入引用的变量,${变量名} es6
            var titl = '谁知道知不知道'
            $('.item').after(`        <li>
            <a href="#">
                ${titl}
                回去
            </a>
        </li>`);

            $('<li>渣浪</li>').insertAfter('.item');

            $('.du').before('');
            $('<p>去</p>').insertBefore('.du');
        })
    </script>
</body>
</html>

替换方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box">
        <h2>alex</h2>
        <h2>alexsb</h2>
        <h1>egon</h1>
    </div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        
        $(function () {
            // 页面中获取的DOM对象.replaceWith(替换的内容)
            $('h2').replaceWith('<a href="#">确实sb</a>');

            // replaceAll()
            $('<p style="color: #ff6700">黑girl</p>').replaceAll('h1');
        })
        
    </script>
</body>
</html>

删除和清空值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div class="box">
        <p style="font-size: 20px; font-weight: 600;">
            alex
        </p>
    </div>
    <button>删除</button>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        
        $(function () {

            $('button').click(function () {
                alert(1);

                // remove()删除节点后,事件也会删除,就是删除了整个标签
                // $(this).remove();
                // var jqBtn = $(this).remove();
                // $('.box').prepend(jqBtn);

                // detach()删除节点后,事件会保留
                $(this).detach();
                var jqBtn = $(this).detach();
                $('.box').prepend(jqBtn);

                // empty()清空
                $('.box').empty();
            })

        })
        
    </script>
</body>
</html>

操作input的value值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="">
        <input type="radio" name="sex"><input type="radio" name="sex"></form>
    <select name="" id="">
        <option value="">1</option>
        <option value="">2</option>
        <option value="" selected="">3</option>
    </select>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $(function () {
            // 单选
            // 原生js用onchange()
            // jq用change()

            // 设置值
            // 加载时,默认选中第一个
            $('input[type=radio]').eq(1).attr('checked',true);
            $('input[type=radio]').change(function () {
                alert(1);
                // 获取值 .val()
                console.log($(this).val());
            });

            // 多选
            // 加载时获取选中项文本
            console.log($('select').find('option:selected').text());
            // 加载时获取选中项索引
            console.log($('select').get(0).selectedIndex);

            // 加载时设置select值为2
            $('select option').get(1).selected=true;
            // selectedIndex是select的属性
            $('select').get(0).selectedIndex=0;

            $('select').change(function () {
                // 获取选中项的值
                console.log($('select option:selected').text());
                console.log($('select').find('option:selected').text());

                // 获取选中项的索引 $('select').get(0)是将jQuery方法转换为js方法

                console.log($('select').get(0).selectedIndex);
                console.log($('select option:selected').index());

                // 设置select的值
                $('select option').get(1).selected=true;
            })
        })

    </script>
</body>
</html>

jquery的位置信息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .box{
            width: 200px;
            height: 200px;
            padding: 10px;
            border: 1px solid red;
        }
    </style>
</head>
<body style="height: 2000px;">
    <div class="box">

    </div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // width() height() 写值是赋值,没值是获取
            $('.box').width();  //获取
            $('.box').height(300);  //设置

            // 内部宽innerWidth() 内部高innerHeight() 包含内部宽+padding 不包含border
            $('.box').innerWidth();
            $('.box').innerHeight(200);
            console.log($('.box').height());

            // 外部宽 outerWidth() 外部高 outerHeight()   包含内部宽+padding+border
            $('.box').outerHeight();

            // offset()    返回值是一个对象,对象包含top和left
            $('.box').offset();
            console.log($('.box').offset().top); //距离页面顶部的距离,与父相子绝定位无关
            console.log($('.box').offset());    //数值只读,不能赋值

            // 滚动的偏移距离 ==>页面卷起的高度和宽度
            // 监听文档的滚动事件jq

            // $(document).scroll(function () {
            //    console.log($(this).scrollTop());
            // });

            // 页面滚动到设定值后消失
            $(document).scroll(function () {
                console.log($(this).scroll().top);
                var scroolTopHeight = $(this).scrollTop();
                var boxOffsetTop = $('.box').offset().top();
                if (scroolTopHeight > boxOffsetTop){
                    $('.box').stop().hide(200);
                }
            })
        })
    </script>
</body>
</html>

原生js的事件流

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>

    <button id="btn">按钮</button>
    <script type="text/javascript">
        var oBtn = document.getElementById('btn');
        // oBtn.onclick = function(){
        //     alert(1);
        // };
        // oBtn.addEventListener(事件,fn,true/false true为捕获事件,false为冒泡阶段,默认为false)
        oBtn.addEventListener('click',function () {
            alert('addEventListener')
        },true)
    </script>

</body>
</html>

事件冒泡的处理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .father{
            width: 300px;
            height: 300px;
            background-color: red;
        }
    </style>
</head>
<body>

    <div class="father">
        <button>按钮</button>
        <a href="http://www.baidu.com">度娘知道</a>
    </div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        // jq中没有捕获阶段,只有冒泡
        $(function () {
            // 给按钮绑定事件
            // 在所有的事件回调函数中,都会有默认的事件对象event
            $('.father button').click(function (event) {
                // event是原生js事件对象
                alert($(this).text());
                // 点了按钮,也会同时点击父div,这个就叫冒泡
                // 阻止冒泡
                event.stopPropagation();
            });
            $('.father').click(function (event) {
               alert('father被点中了');
            });
            $('a').click(function (event) {
               event.preventDefault(); //阻止默认事件
                alert('度娘不在');
                event.stopPropagation();//阻止冒泡

                return false //上面两句可以合成这一句
            });

        })
    </script>
</body>
</html>

抽屉评论

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        .commentBtn{
            font-size: 30px;
            color: #fff;
        }
        .box{
            width: 300px;
            line-height: 70px;
            text-align: center;
            background-color: #666;
            position: relative;
        }
        .comment{
            position: relative;
            width: 300px;
            height: 500px;
            background-color: #999;
        }
        .comment span.close{
            position: absolute;
            top: 0;
            right: 10px;
            color: #000;
            cursor: pointer;
        }
        .comment button.hidden{
            position: absolute;
            bottom: 0;
            right: 0;
        }
    </style>
</head>
<body>
    <div class="box">
        <span class="commentBtn">评论</span>
        <div class="comment" style="display: none;">
            <span class="close active">X</span>
            <button class="hidden active">收起</button>
        </div>
    </div>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">

        $(function () {
            // 点击评论展开
            $('.commentBtn').click(function (event) {
               $('.comment').stop().slideDown(500);
               event.stopPropagation();
            });
            $('.comment span.close, .comment button.hidden').click(function (event) {
                $('.comment').slideUp(500);
                event.stopPropagation();
            });
            $('body').click(function (event) {
                $('.comment').slideUp(500);
            })
        });
    </script>
</body>
</html>

事件对象event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <button>按钮</button>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $('button').click(function (event) {
                // currentTarget是当前事件的目标对象
                console.log(event.currentTarget);
                //target是事件的触发对象 js对象
                console.log(event.target);
                // 在用事件的时候,99%都需要阻止冒泡,这时候currentTarget就和target一样了

                // 获取事件按钮值
                console.log(event.target.innerText);
                console.log($(event.target).text());
                console.log($(this).text());
            });
            $('body').click(function (event) {
                console.log(event.currentTarget);
                console.log(event.target);
            });
            $('html').click(function (event) {
                console.log(event.currentTarget);
                console.log(event.target);
            });

        });
    </script>
</body>
</html>

监听input输入值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        
    </style>
</head>
<body> 
    <div>
        <input type="text" name="user">
        <p class="comment"></p>
        <script type="text/javascript" src="jquery-3.3.1.js"></script>
        <script type="text/javascript">
            $(function () {
                // jq中没有这种方法,需要用原生js的oninput方法
                // 这种叫双向的数据绑定
               $('input').get(0).oninput = function (event) {
                   //实时获取值
                   console.log(event.target.value);
                   // 实时赋值
                   $('.comment').text(event.target.value);
               }
            });
        </script>
    </div>

</body>
</html>

jQuery的单双击事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button>按钮</button>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 问题:双击实际上是调用了两次单击,两次单击之间的默认时间是300ms,如果小于300ms表示双击
            timer = null;
            $('button').click(function (event) {
                clearTimeout(timer);
                timer = setTimeout(function () {
                    console.log('单击了');
                },300);

            });
            $('button').dblclick(function () {
                clearTimeout(timer);
                console.log('双击了');
            });

            /* 解决单双击冲突问题,双击是阻止两次单击的响应
                1.var 全局变量timer=null初始定时器
                2.单击双击都使用clearTimeout(timer)方法清除定时器
                3.单击事件手动设置300毫秒定时器,以响应单击操作
                    timer = setTimeout(function () {
                    console.log('单击了');
                    },300);
            */
            
        });
    </script>
</body>
</html>

jQuery的鼠标移入事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .father{
            width: 200px;
            height: 200px;
            background-color: red;
        }
        .child{
            width: 100px;
            height: 100px;
            background-color: #666;
        }
    </style>
</head>
<body>
    <div class="father">
        <p class="child">
            alex
        </p>
    </div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 鼠标穿过备选元素和备选元素的子元素,会触发此事件
            // $('.father').mouseover(function () {
            //     console.log('移入了');
            // });
            // $('.father').mouseout(function () {
            //     console.log('移出了');
            // });
            // 鼠标只穿过备选元素,会触发此事件
            $('.father').mouseenter(function () {
                console.log('移入了');
            });
            $('.father').mouseleave(function () {
                console.log('移出了');
            });
        })
    </script>
</body>
</html>

移入移出事件demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        *{
            padding: 0px;
            margin: 0px;
        }
        .shopCart{
            position: relative;
            width: 100px;
            height: 50px;
            line-height: 50px;
            background-color: #666;
        }
        .content{
            position: absolute;
            top: 50px;
            width: 300px;
            height: 300px;
            background-color: #999;
        }
    </style>
</head>
<body>
    <div class="shopCart">
        <span>购物车</span>
        <div class="content" style="display: none;">

        </div>
    </div>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // $('.shopCart').mouseenter(function () {
            //     $('.content').stop().slideDown(300);
            //     // $(this).children('.content').stop().slideDown(300);
            // });
            // $('.shopCart').mouseleave(function () {
            //     $('.content').stop().slideUp(300);
            //     // $(this).children('.content').stop().slideUp(300);
            // });

            // 合成in/out方法hover()
            $('.shopCart').hover(function () {
                $(this).children('.content').stop().slideDown(300);
            },function () {
                $(this).children('.content').stop().slideUp(300);
            });
        });
    </script>
</body>
</html>

表单事件的select事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <form action="http://www.baidu.com/s" method="get">
        <input type="text" name="wd">
        <input type="submit" value="搜索">
    </form>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // select方法是文本输入的内容被选中时才会调用
            $('input[type=text]').select(function () {
               console.log('文本内容被选中了');
            });

            // 原生js的onsubmit方法 jq是submit()方法
            $('form').submit(function (event) {
                // 需求:禁止原生action,自定义请求
                event.preventDefault();
                alert('禁止操作');
            });
        });
    </script>
</body>
</html>

鼠标的聚焦与失焦,键盘操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <input type="text" name="user">
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 获取焦点,页面加载时直接聚焦到文本输入框中
            $('input[type=text]').focus();
            setTimeout(function () {
                // 失焦
                $('input[type=text]').blur();
            },2000);
            $('input[type=text]').focus(function () {
                console.log('获取焦点');
            });
            $('input[type=text]').blur(function () {
                console.log('失去焦点');
            });

            // 获取键盘事件
            $('input[type=text]').keyup(function (event) {
                // console.log('键盘按下了');
                // // 获取键码
                // console.log(event);
                
                switch (event.keyCode) {
                    case 13:
                        console.log('回车被按下了');
                        console.log($(this).val());
                        break;
                }
            });

        });
    </script>
</body>
</html>

事件委托

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <ul>
        <li>alex</li>
        <li>egon</li>
    </ul>
    <button>添加</button>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            /*
            $('ul>li').click(function () {
                alert($(this).text());
            });
            */

            // 需要用下面的方法绑定事件
            $('ul').on('click', 'li',function (event) {
               alert($(this).text());
            });

            // 通过事件动态的往ul中添加li,新添加的li不会继承方法,需要考虑采用“事件委托”,利用冒泡原理把事件加在父级上 ,触发效果

            $('button').click(function () {
                $('ul').append('<li>黑girl</li>')
            });
        });
    </script>

</body>
</html>

jQuery的ajax和get方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--<div class="box"></div> //视图-->
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        /*  动态页面:在不重载整个网页的情况下,ajax通过后台加载数据,并在网页上显示
            数据 ==》页面
            数据驱动视图,数据的更改会直接在页面上有相应的变化,但数据不是无缘无故的显示到视图上,是通过控制器的处理来
            显示到视图上的

        /*
            架构模式也称设计模式
            设计模式是一些开发者在开发框架时提出的思想
            MVC Model(数据) View(视图) Controller(控制器)
            jq的方法就是控制器
        */
        // var val = '这里改了,页面也会改'; //数据
        // $('.box').text('这里的值会在页面上显示');  //方法.控制器
        // $('.box').text(val);

        // ajax的写法
        $(function () {
           $.ajax({
               url: 'http://localhost',
               type: 'get',
               success: function (data) {
                   console.log(data);
               },
               error: function (err) {
                   console.log(err);
               }
           });
        });
    </script>

</body>
</html>

ajax的post方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <form action="">
        <input type="text" name="user">
        <input type="submit" value="提交">
    </form>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function (){
            $('form').submit(function (event) {
                //阻止form表单的默认事件
                event.preventDefault();

                var userVal = $('input[type=text]').val();
                console.log(userVal);
                    // 与后端交互
                    $.ajax({
                        url:'http://localhost/create',
                        type:'post',
                        data:{
                            name:userVal
                        },
                        success:function (data) {
                            console.log(data);
                        },
                        error:function (err) {
                            console.log(err);
                        }
                    });
            });
        });
    </script>
</body>
</html>

 

posted @ 2019-01-11 15:20  李卓航  阅读(372)  评论(0编辑  收藏  举报