02-01 jQuery

一. 什么是jQuery?

jQuery内部封装了原生jS, jQuery类似于python里面的模块, 在前端jQuery是一个提供了额外功能的框架又或者说类库. 
jQuery设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。 

二. jQuery的优势

  1. 一款轻量级的JS框架。jQuery核心js文件才几十kb,不会影响页面加载速度。
  2. 丰富的DOM选择器,jQuery的选择器用起来很方便,比如要找到某个DOM对象的相邻元素,JS可能要写好几行代码,而jQuery一行代码就搞定了,再比如要将一个表格的隔行变色,jQuery也是一行代码搞定。
  3. 链式表达式。jQuery的链式操作可以把多个操作写在一行代码里,更加简洁。
  4. 事件、样式、动画支持。jQuery还简化了js操作css的代码,并且代码的可读性也比js要强。
  5. Ajax操作支持。jQuery简化了AJAX操作,后端只需返回一个JSON格式的字符串就能完成与前端的通信。
  6. 跨浏览器兼容。jQuery基本兼容了现在主流的浏览器,不用再为浏览器的兼容问题而伤透脑筋。
  7. 插件扩展开发。jQuery有着丰富的第三方的插件,例如:树形菜单、日期控件、图片切换插件、弹出窗口等等基本前端页面上的组件都有对应插件,并且用jQuery插件做出来的效果很炫,并且可以根据自己需要去改写和封装插件,简单实用。

三. jQuery内容

选择器
筛选器
样式操作
文本操作
属性操作
文档处理
事件
动画效果
插件
each、data、Ajax(重点)

下载链接:jQuery官网

中文文档:jQuery AP中文文档

四. jQuery版本

  • 1.x:兼容IE678,使用最为广泛的,官方只做BUG维护,功能不再新增。因此一般项目来说,使用1.x版本就可以了,最终版本:1.12.4 (2016年5月20日)
  • 2.x:不兼容IE678,很少有人使用,官方只做BUG维护,功能不再新增。如果不考虑兼容低版本的浏览器可以使用2.x,最终版本:2.2.4 (2016年5月20日)
  • 3.x:不兼容IE678,只支持最新的浏览器。需要注意的是很多老的jQuery插件不支持3.x版。目前该版本是官方主要更新维护的版本。

补充: 维护IE678是一件让人头疼的事情,一般我们都会额外加载一个CSS和JS单独处理。值得庆幸的是使用这些浏览器的人也逐步减少,PC端用户已经逐步被移动端用户所取代,如果没有特殊要求的话,一般都会选择放弃对678的支持。

五. jQuery的2种导入方式

jQuery在使用的时候也需要导入, 但是它的文件非常的小(几十KB) 基本不影响网络速度. 压缩过的大概80KB左右, 未压缩的大概240KB左右

# 1. 将文件下载到本地直接导入(压缩: jquery-3.5.1.min . 未压缩: jquery-3.5.1)
    好处: 没有网也可以正常使用
    坏处: 需要重复书写,文件路径还要固定
        pycharm自定义代码模块功能 自动添加固定的代码: settings->editor->file and code template
        
# 2. CDN服务
    CDN的概念: 内容分发网络
    参考网站: bootcdn. 前端相关的应用程序都有免费的cdn服务(提示: CDN有免费的也有收费的)

    好处: 无需下载对应的文件,直接走网络请求使用
    坏处: 必须要有网络
    
    引入: <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

bootcdn网址: 点我有你好看

六. jQuery基础语法

提示: jQuery在使用之前 一定要确保已经导入了

jQuery(selector).action()
    秉持着jQuery的宗旨 jQuery简写成 $ 
    简写: $(selector).action()

# jQuery与js代码对比
// 例子: 将p标签内部的文本颜色改为红色
// 原生js代码操作标签
    let pEle = document.getElementById('d1')
    pEle.style.color = 'red'

// jQuery操作标签
$('p').css('color','blue')

七. jQuery对象与标签对象之间的转换

jQuery对象就是通过jQuery包装DOM对象后产生的对象。jQuery对象是 jQuery独有的。如果一个对象是 jQuery对象,那么它就可以使用jQuery里的方法:例如$(“#i1”).html()。

$("#i1").html()的意思是:获取id值为 i1的元素的html代码。其中 html()是jQuery里的方法。

相当于: document.getElementById("i1").innerHTML;

虽然 jQuery对象是包装 DOM对象后产生的,但是 jQuery对象无法使用 DOM对象的任何方法,同理 DOM对象也没不能使用 jQuery里的方法。

$('div')[0] jq对象转标签对象
$(divEle)   标签对象转jq对象

总结

# jq功能: jQuery内部封装了原生的js代码(还额外添加了很多的功能), 能够让你通过书写更少的代码 完成js操作. 类jQuery似于python里面的模块  在前端模块不叫模块  叫 “类库”

# jq宗旨: write less do more
    
# jq版本: 1xx, 2xx, 3xx 其中2xx,3xx不兼容IE678, 这里我们使用jQuery的时候就不需要考虑浏览器兼容问题. 因为IE678基本上被淘汰了.
    
# jq2种导入模式:
    1. 将jq文件下载本地
    2. 直接引用提供jq的CDN服务. 例如: 免费的bootcdn
    补充: 借助pycharm提供的js文件模板实现每次创建文件默认帮我们导入jq.

# jq基本语法:
    jQuery(选择器).action()
    简写: $(选择器).action()

# jq对象与标签对象之间的转换:
    $('div')[0] jq对象转标签对象
    $(divEle)   标签对象转jq对象

九. 查找标签

1. 基本选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="d1">div
    <span>div>span</span>
    <p>div>p
        <span>div>p>span</span>
    </p>
</div>
<p class="c1">p</p>
<span>span</span>

<script>
    /*一. 基本选择器: id选择器, 类选择器, 元素(标签)选择器, 通配符选择器*/
    console.log($('#d1'));   // id选择器
    console.log($('.c1'));    // 类选择器
    console.log($('span'));   // 元素(标签)选择器
    console.log($('*'));   // 通配符选择器

    /*二. jQuery对象与标签对象之见的转化*/
    // 注意!!: 虽然它们类型都是对象类型, 但是DOM操作出来的对象由DOM类生成, 由jQuery操作出来的对象由jQuery类生成. 两者之间是由不同的类创建, 所以不同的对象调用的方法只能是实例化自己类里面的.
    let divELe = document.getElementById('d1');
    console.log(typeof divELe);    // object
    console.log(typeof $('#d1'));  // object

    console.log($('#d1')[0]);  // jQuery对象变成标签对象
    console.log($(divELe));     // 标签对象转jQuery对象


    // 总结
    /*
    jQuery基本选择器:
        id选择器: $('#d1');
        类选择器: $('.d1');
        元素(标签)选择器: $('span');

    jQuery对象与标签对象之间的转换:
        jQuery对象变成标签对象: 索引取值
            $('#d1')[0];
        标签对象转jQuery对象: 使用jQuery类包含
            $(divEle);
    */
</script>
</body>
</html>

2. 组合选择器/分组与嵌套

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<span>span</span>
<span>span</span>
<div id="d1">div
    <span>div>span</span>
    <p id="d2">div>p
        <span>div>p>span</span>
    </p>
    <span>div>span</span>
</div>
<div class="c1">div</div>
<span>span</span>
<span>span</span>

<script>
    /*一. 组合选择器: 后代选择器, 子代选择器, 毗邻选择器, 弟弟选择器*/
    console.log($('div span'));  // 后代选择器
    /*
    S.fn.init(3) [span, span, span, prevObject: S.fn.init(1)]
    0: span
    1: span
    2: span
    length: 3
    prevObject: S.fn.init [document]
    __proto__: Object(0)
    */

    console.log($('div>span'));  // 子代选择器
    /*
    S.fn.init(2) [span, span, prevObject: S.fn.init(1)]
    0: span
    1: span
    length: 2
    prevObject: S.fn.init [document]
    __proto__: Object(0)
    */

    console.log($('div+span'));  // 毗邻选择器
    /*
    S.fn.init [span, prevObject: S.fn.init(1)]
    0: span
    length: 1
    prevObject: S.fn.init [document]
    __proto__: Object(0)
    */

    console.log($('div~span'));  // 弟弟选择器
    /*
    S.fn.init(2) [span, span, prevObject: S.fn.init(1)]
    0: span
    1: span
    length: 2
    prevObject: S.fn.init [document]
    __proto__: Object(0)
    */

    /*二. 分组与嵌套*/
    console.log($('div,p'));  // 分组
    /*
    S.fn.init(3) [div#d1, p#d2, div.c1, prevObject: S.fn.init(1)]
    0: div#d1
    1: p#d2
    2: div.c1
    length: 3
    prevObject: S.fn.init [document]
    __proto__: Object(0)
    */

    console.log($('#d1,p'));  // 嵌套
    /*
    S.fn.init(2) [div#d1, p#d2, prevObject: S.fn.init(1)]
    0: div#d1
    1: p#d2
    length: 2
    prevObject: S.fn.init [document]
    __proto__: Object(0)
    */


    // 总结
    /*
    组合选择器:
        后代选择器: $('div span');
        子代选择器: $('div>span');
        毗邻选择器: $('div+span');
        弟弟选择器: $('div~span');

    分组与嵌套:
        分组: $('div,span');
        嵌套: $('#d1,span');
    */
</script>
</body>
</html>

3. 基本筛选器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<ul>
    <li>101</li>
    <li>102</li>
    <li>103</li>
    <li>104</li>
    <li>105</li>
    <li>106</li>
    <li class="c1">107</li>
    <li>108</li>
    <li id="d1">109</li>
    <li>110</li>
</ul>

<div>div
    <p>div>p</p>
    <span>div>span</span>
</div>
<div>div
    <a href="">div>a</a>
</div>

<script>
    console.log($('ul li'));

    console.log($('ul li:first'));  // 大儿子
    console.log($('ul li:last'));   // 小儿子

    console.log($('ul li:even'));  // 偶数索引 0包含在内
    console.log($('ul li:odd'));   // 奇数索引

    console.log($('ul li:eq(1)'));  // 等于索引(放索引)
    console.log($('ul li:gt(2)'));  // 大于索引
    console.log($('ul li:lt(2)'));  // 小于索引

    console.log($('ul li:not("#d1")'));  // 排除满足条件的标签,要剩下来的所有
    console.log($('div:has("p")'));    // 选取出包含一个或多个标签在内的标签


    // 总结
    /*
    注意: 都是冒号:起手
    :first :last
    :even  :odd
    :eq(index) :gt(index) :lt(index)
    :not("") :has("")
    */
</script>
</div>
</body>
</html>

4. 属性选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" username="jason">
<input type="text" username="egon">
<p username="egon"></p>

<script>
    console.log($('[username]'));
    console.log($('[username="egon"]'));
    console.log($('p[username="egon"]'));
</script>
</body>
</html>

5. 表单筛选器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="">
    <p>username:<input type="text"></p>
    <p>password:<input type="password"></p>
    <input type="checkbox" value="111">111
    <input type="checkbox" value="111" checked>222
    <input type="checkbox" value="111">333

    <select name="" id="">
        <option value="">111</option>
        <option value="">222</option>
        <option value="" selected>333</option>
    </select>

    <input type="button" value="按钮">

    <input type="text" readonly>
</form>

<script>
    console.log($('[type="text"]'));
    console.log($(':text'));  // 与上面等价

    console.log($(':password'));

    /*特殊情况*/
    // :checked: 它会将checked和selected都拿到
    // :selected: 它不会 只拿selected
    console.log($(':checked'));
    console.log($(':selected'));

    console.log($('input:checked'));  // 对 :checked 需要特殊对待

    // 总结:
    /*
    表单属性:
        :text   :password
        :date
        :file
        :radio  :checkbox
        :submit :button :reset
        :hidden

    表单对象属性:
        :enabled
        :disabled
        :checked  特殊对待: input:checked
        :selected
    */
</script>
</body>
</html>

6. 筛选器方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<span id="d1">span</span>
<span>span</span>
<div id="d2">
    <span>div>span</span>
    <p>div>p
        <span id="d3">div>p>span</span>
    </p>
    <span>div>span</span>
</div>
<span>span</span>
<span>span</span>
<span class="c1">span</span>

<script>
    console.log($('#d1').next());            // 同级别下一个
    console.log($('#d1').nextAll());         // 同级别下所有
    console.log($('#d1').nextUntil('.c1'));  // 同级下所有直到.c1停止(不包括指定的)

    console.log($('.c1').prev());            // 同级别上一个
    console.log($('.c1').prevAll());         // 同级别上所有
    console.log($('.c1').prevUntil('#d1'));  // 同级别上所有直到#d1停止(不包括指定的)

    console.log($('#d3').parent());  // 父标签
    console.log($('#d3').parent().parent());
    console.log($('#d3').parent().parent().parent());
    console.log($('#d3').parent().parent().parent().parent());
    console.log($('#d3').parent().parent().parent().parent().parent());  // S.fn.init [document, prevObject: S.fn.init(1)] (通过这种方式最顶部可以返回到document)
    console.log($('#d3').parents());  // 返回所有父标签. 最顶部可以只能到达html层
    console.log($('#d3').parentsUntil('body'));  // 直到body停止(不包括指定的)

    console.log($('#d2').children());  // 儿子们

    console.log($('#d2').siblings());  // 同级别上下所有


    /*与组合选择器等价方法*/
     console.log($('div p'));
     console.log($('div').find('p'));  // find从某个区域内筛选出想要的标签(与上面等价)

    /*与基本筛选器等价方法*/
    console.log($('div span:first'));
    console.log($('div span').first());

    console.log($('div span:last'));
    console.log($('div span').last());

    console.log($('div span:not("#d3")'));
    console.log($('div span').not('#d3'));


    // 总结
    /*
    同级别上一个: .prev()
    同级别上所有: .prevAll()
    同级别上所有直到停止(不包括指定的): .prevUntil(停止条件)

    同级别下一个: .next()
    同级别下所有: .nextAll()
    同级别下所有直到停止(不包括指定的): .nextUntil(停止条件)

    父标签:   .parent()     可以获取html之上的逻辑层document
    父标签们: .parents()    获取的所有父标签们只到达html为止
    父标签们直到直到停止(不包括指定的): .parentsUntil(停止条件)

    儿子们: .children()

    同级别上下所有: .siblings()

    等价方法:
        $('div span')              等价    $('div').find('span')
        $('div span:first')        等价    $('div span').first('span')
        $('div span:last')         等价    $('div span').first('last')
        $('div span:not(".c1")')   等价    $('div span').not('.c1')
    */
</script>
</body>
</html>

7. 总结

# 基本选择器:
    id选择器: $('#d1')
    类选择器: $('.c1')
    元素/标签选择器: $('div')
    通配符选择器: $('*')

# 组合选择器, 分组与嵌套:
    组合选择器:
        后代选择器: $('div span')
        子代选择器: $('div>span')
        毗邻选择器: $('div+span')
        弟弟选择器: $('div~span')
    分组与嵌套:
        分组: $('div,span')
        嵌套: $('#d1,span')

# 基本筛选器:
    第一个: $('ul li:first')
    最后一个: $('ul li:last')

    索引为偶数: $('ul li:even')
    索引为奇数: $('ul li:odd')

    等于索引值: $('ul li:eq(0)')
    大于索引值: $('ul li:gt(2)')
    小于索引值: $('ul li:lt(2)')

    排除满足条件, 要剩下所有: $('ul li:not("#d1")')
    选取包含一个或多个在内的: $('div:has("p")')

# 属性选择器:
    $('[username]')
    $('[username="egon"]')
    $('input[username="egon"]')
    
# 表单选择器:
    表单属性:
        $('[type=text]')
        替代: $(':text')
        :text :password
        :date
        :file
        :hidden
        :radio  :checkbox
        :button :submit :reset
    表单对象属性:
        :enabled
        :disabled
        :checked  特殊对待: input:checked
        :selected

# 筛选器方法:
    同级别上一个: .prev()
    同级别上所有: .prevAll()
    同级别上所有直到什么停止(不包含指定的): .prevUntil(停止条件)

    同级别下一个: .next()
    同级别下所有: .nextAll()
    同级别下所有直到什么停止(不包含指定的): .nextUntil(停止条件)

    父标签: .parent()     最高可以获取抽象层docuemnt
    父标签所有: .parents() 获取的所有父标签中最高只能获取到html
    父标签所有直到什么停止(不包含指定的): .parentsUntil(停止条件)

    儿子们: .children()

    同级别上下所有: .siblings()

    等价方法:
        $('div span')  <==> $('div').find('span')
        $('ul li:first') <==> $('ul li').find()
        $('ul li:last')  <==> $('ul li').last()
        $('ul li:not("#d1")')  <==> $('ul li').not('#d1')

十. jQuery练习题

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery选择器筛选器练习</title>
  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <style>

    .my-padding {
      padding: 10px 0;
    }

    .my-dark {
      background-color: #f5f5f5;
    }

    .footer {
      background: #111;
      font-size: 0.9em;
      position: relative;
      clear: both;
    }
    .my-white {
      color: #ffffff;
    }

    body {
      margin: 0;
    }
    #progress {
      height: 2px;
      background-color: #b91f1f;
      transition: opacity 500ms linear;
    }
    #progress.done{
      opacity: 0;
    }
  </style>
</head>
<body>
<div id="progress"></div>
<!--导航栏开始-->
<nav class="navbar navbar-inverse my-nav">
  <div class="container">
    <!-- 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="http://www.oldboyedu.com/"><strong>OldBoy Edu</strong></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><a href="#">Python学院<span class="sr-only">(current)</span></a></li>
        <li><a href="#">Linux学院</a></li>
        <li><a href="http://luffy.oldboyedu.com">路飞学城</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">好好学习</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
             aria-expanded="false">联系我们<span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Jason</a></li>
            <li><a href="#">Sean</a></li>
            <li><a href="#">Oscar</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Jason</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<!--导航栏结束-->


<div class="container">

  <div class="jumbotron">
    <div id="i1" class="container">
      <h1 class="c1">Jason</h1>
      <h1 class="c1">带你学习jQuery</h1>
      <p id="p1"><a class="btn btn-primary btn-lg" href="https://q1mi.github.io/Blog/2017/07/10/about_jQuery/"
                    role="button">查看更多</a></p></div>
  </div>
  <hr>
  <div class="row">
    <div class="col-md-12">
      <table class="table table-bordered table-striped">
        <thead>
        <tr>
          <th>#</th>
          <th>姓名</th>
          <th>爱好</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr>
          <th>1</th>
          <td>Jason</td>
          <td>学习</td>
          <td>
            <button class="btn btn-warning">编辑</button>
            <button class="btn btn-danger">删除</button>
          </td>
        </tr>
        <tr>
          <th>2</th>
          <td>Oscar</td>
          <td>大饼</td>
          <td>
            <button class="btn btn-warning">编辑</button>
            <button class="btn btn-danger">删除</button>
          </td>
        </tr>
        <tr id="tr3">
          <th>3</th>
          <td>Egon</td>
          <td>吹牛逼</td>
          <td>
            <button class="btn btn-warning">编辑</button>
            <button class="btn btn-danger">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>

  <hr>
  <div class="row">
    <div class="col-md-12">
      <form id="f1">
        <div class="form-group">
          <label for="exampleInputEmail1">邮箱</label>
          <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">密码</label>
          <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
        </div>
        <div class="form-group">
          <label for="exampleInputFile">上传头像</label>
          <input type="file" id="exampleInputFile">
          <p class="help-block">只支持img格式。</p>
        </div>
        <button id="btnSubmit" type="submit" class="btn btn-default">提交</button>
      </form>
    </div>
  </div>

  <hr>

  <div class="row">
    <div class="col-md-12">
      <div class="checkbox-wrapper">
        <div class="panel panel-info">
          <div class="panel-heading">jQuery学习指南</div>
          <div id="my-checkbox" class="panel-body">
            <div class="checkbox">
              <label>
                <input type="checkbox" value="0">
                jQuery一点都不难
              </label>
            </div>
            <div class="checkbox">
              <label>
                <input type="checkbox" value="1" checked>
                jQuery一学就会
              </label>
            </div>
            <div class="checkbox">
              <label>
                <input type="checkbox" value="2">
                jQuery就要多练
              </label>
            </div>

            <div class="checkbox">
              <label>
                <input type="checkbox" value="3" disabled>
                jQuery学不好
              </label>
            </div>
          </div>
        </div>
      </div>
      <hr>
      <div class="radio-wrapper">

        <div class="panel panel-info">
          <div class="panel-heading">我来老男孩之后...</div>
          <div class="panel-body">
            <div class="radio">
              <label>
                <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
                我的心中只有学习
              </label>
            </div>
            <div class="radio">
              <label>
                <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
                学习真的太TM有意思了
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <hr>

  <div>
    <i class="fa fa-hand-pointer-o fa-lg fa-rotate-90" aria-hidden="true"></i>
    <a class="btn btn-success" href="http://jquery.cuishifeng.cn/">jQuery中文API指南</a>
  </div>

  <hr>

  <div class="row">
    <div class="col-md-12">
      <h2>练习题:</h2>
      <ol id="o1">
        <li>找到本页面中id是<code>i1</code>的标签</li>
        <li>找到本页面中所有的<code>h2</code>标签</li>
        <li>找到本页面中所有的<code>input</code>标签</li>
        <li>找到本页面所有样式类中有<code>c1</code>的标签</li>
        <li>找到本页面所有样式类中有<code>btn-default</code>的标签</li>
        <li>找到本页面所有样式类中有<code>c1</code>的标签和所有<code>h2</code>标签</li>
        <li>找到本页面所有样式类中有<code>c1</code>的标签和id是<code>p3</code>的标签</li>
        <li>找到本页面所有样式类中有<code>c1</code>的标签和所有样式类中有<code>btn</code>的标签</li>
        <p id="p2" class="divider"></p>
        <li>找到本页面中<code>form</code>标签中的所有<code>input</code>标签</li>
        <li>找到本页面中被包裹在<code>label</code>标签内的<code>input</code>标签</li>
        <li>找到本页面中紧挨在<code>label</code>标签后面的<code>input</code>标签</li>
        <li>找到本页面中id为<code>p2</code>的标签后面所有和它同级的<code>li</code>标签</li>
        <p id="p3" class="divider"></p>
        <li>找到id值为<code>f1</code>的标签内部的第一个input标签</li>
        <li>找到id值为<code>my-checkbox</code>的标签内部最后一个input标签</li>
        <li>找到id值为<code>my-checkbox</code>的标签内部没有被选中的那个input标签</li>
        <li>找到所有含有<code>input</code>标签的<code>label</code>标签</li>
      </ol>
    </div>
  </div>
</div>

<div class="my-dark my-padding">
  <div class="container">
    <div class="col-sm-8 my-center">
      <p>写很少的代码,做很多的事。</p>
      <h4>所以说</h4>
      <p>学好jQuery真的很重要,学好jQuery真的很重要,学好jQuery真的很重要。</p>
    </div>
  </div>
</div>

<div class="footer">
  <div class="row">
    <div class="col-md-12 text-center">
      <span class="my-white">&copy;2020 Jason</span>
    </div>
  </div>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

十一. 操作标签

1. CSS 类操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="c1 c2 c3"></div>

<script>
    /*
    js中的类操作                     jq中的类操作
    标签对象.classList.add()         jq对象.addClass()
    标签对象.classList.remove()      jq对象.removeClass()
    标签对象.classList.contains()    jq对象.hasClass()
    标签对象.classList.toggle()      jq对象.toggleClass()
    */
    $('.c1').addClass('c4');
    $('.c1').hasClass('c4');
    $('.c1').removeClass('c2');
    $('.c1').toggleClass('c3');
</script>
</body>
</html>

2. CSS 样式操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<p>111</p>
<p>222</p>
<p>333</p>

<script>
    // 需求: 一行代码将第一个p标签变成红色, 第二个p标签变成绿色, 第三个变成黄色.
    /*
    jQuery的链式操作 使用jQuery可以做到一行代码操作很多标签
    jQuery对象调用jQuery方法之后返回的还是当前jQuery对象 也就可以继续调用其他方法. 这里我们通过python代码示例:
    class MyClass(object):
        def func1(self):
            print('func1')
            return self

        def func2(self):
            print('func2')
            return self
    obj = MyClass()
    obj.func1().func2()
    */
    $('p').css('color', 'red').next().css('color', 'green').next().css('color', 'yellow');

    /*
    $('p').css('color', 'red');
    w.fn.init(3) [p, p, p, prevObject: w.fn.init(1)]

    $('p').css('color', 'red').next().css('color', 'green');
    w.fn.init(3) [p, p, script, prevObject: w.fn.init(3)]

    $('p').css('color', 'red').next().css('color', 'green').next().css('color', 'yellow');
    w.fn.init(3) [p, script, div, prevObject: w.fn.init(3)]
    */
</script>
</body>
</html>

3. 位置操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            margin: 0;
        }
        div {
            width: 300px;
            height: 300px;
            background-color: red;
            position: relative;
            top: 100px;
            left: 100px;
        }
        p {
            width: 100px;
            height: 100px;
            background-color: pink;
            text-align: center;
            line-height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -50px;
            margin-left: -50px;
        }
    </style>
</head>
<body>
<h1 style="height: 2000px; width: 1000px"></h1>
<div>
    <p>ppp</p>
</div>

<script>
    $('div').offset();   // {top: 100, left: 100} (左上角顶点相对于浏览器窗口)
    $('p').position();   // {top: 150, left: 150} (中心点相对于父标签)

    $(window).scrollTop());  // 获取匹配元素相对滚动条顶部的偏移(括号内不加参数就是获取)
    $(window).scrollTop(0);     // 加了参数就是设置
    $(window).scrollLeft(0);    // 获取匹配元素相对滚动条左侧的偏移。(加了参数就是设置)


    // 总结
    /*
    掌握:
        右侧滚动条:
            获取: $(window).scrollTop()
            设置: $(window).scrollTop(0)
        左侧滚动条:
            获取: $(window).scrollLeft()
            设置: $(window).scrollLeft(0)
    了解:
        左上角顶点相对窗口: .offset()
        中心点相对父元素:   .position()
    */
</script>
</body>
</html>

4. 尺寸

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        p {
            margin: 1px 2px 3px 4px;
            padding: 4px 3px 2px 1px;
        }
    </style>
</head>
<body>
<p>111</p>

<script>
    $('p').height();  // 文本
    $('p').width();

    $('p').innerHeight();  // 文本+padding
    $('p').innerWidth();

    $('p').outerHeight();  // 文本+padding+border
    $('p').outerWidth();

    // 总结
    /*
    文本:
        文本宽度: .width()
        文本高度: .height()

    文本+padding
        文本宽度+padding宽度:  .innerWidth()
        文本高度+padding高度:  .innerHeight()

    文本+padding+border
        文本宽度+padding宽度+border宽度: .outerWidth()
        文本高度+padding高度+border高度: .outerHeigh()
    */
</script>
</body>
</html>

5. 文本操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div>
    <p>
        有些话听听就过去了,不要在意,都是成年人!
    </p>
</div>

<script>
    /*
    js中的文本操作              jq中的文本操作:
    标签对象.innerText         jq对象.text()    括号内不加参数就是获取
    标签对象.innerText=''      jq对象.text('')  加了就是设置
    标签对象.innerHTML         jq对象.html()
    标签对象.innerHTML=''      jq对象.html('')
    */

    $('div').text();
    $('div').html();

    $('div').text('你们都是我的大宝贝');
    $('div').html('你个臭妹妹');

    $('div').text('<h1>你们都是我的大宝贝</h1>');
    $('div').html('<h1>你个臭妹妹</h1>');
</script>
</body>
</html>

6. 值操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="d1">
<input type="file" id="d2">

<input type="checkbox" name="hobby" value="111">111
<input type="checkbox" name="hobby" value="222">222
<input type="checkbox" name="hobby" value="333">333

<script>
    /*
    js中的值操作            jq中的值操作:
    .value                .val()    括号内不加参数就是获取
    .value=''             .val('')  加了就是设置
    .files                提示: jq中没有获取文件对象操作
    .files[0]
    */

    $('#d1').val();
    $('#d1').val('520快乐';

    // 如果jq想要获取文件对象, 需要先拿到获取的jq对象转成js对象, 再进行.files()操作.
    $('#d2')[0].value;
    $('#d2')[0].files;
    $('#d2')[0].files[0];
</script>
</body>
</html>

7. 属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p id="d1" username="jason"></p>


<input type="checkbox" value="111" name="hobby" id="d2">
<input type="checkbox" value="222" name="hobby" checked id="d3">
<input type="checkbox" value="333" name="hobby" id="d4">


<script>
    /*
    js中的值操作                                     jq中的值操作:
    标签对象.setAttribute(attrName, attrValue)       jq对象.attr(attrName, attrValue)
    标签对象.getAttribute(attrName)                  jq对象.attr()
    标签对象.removeAttribute(attrName)               jq对象.removeAttr('username')
                                                   jq对象.prop('checked')
                                                   jq对象.prop('checked', true)
    */
    let $pEle = $('p');
    // 获取
    $pEle.attr('id');
    $pEle.attr('class');

    // 设置
    $pEle.attr('class', 'c1');
    $pEle.attr('id', 'd6666');
    $pEle.attr('username', 'egon');
    $pEle.attr('password', '123');

    // 删除
    $pEle.removeAttr('password');

    
    /*
    提示: 对于标签上有的能够看到的属性和自定义属性用attr
    对于返回布尔值比如checkbox radio option是否被选中用prop 全称 property
    */
    $('#d2').attr('checked');  // undefined
    $('#d3').attr('checked');  // "checked"
    $('#d4').attr('checked');  // undefined
    $('#d3').attr('checked');  // 对于上面已经设置了, 手动的勾选或者删除勾选以后以后查看是无效的任然是 "checked"


    $('#d2').prop('checked');  // false
    $('#d3').prop('checked');  // true
    $('#d4').prop('checked');  // false
    $('#d4').prop('checked');  // #d4没有设置默认checked默认没有选中, 手动勾选以后使用prop可以发现值变成了true. 这种就可以获取用户的操作.
    $('#d3').prop('checked',true);  // 可以指定true, false达到勾选的功能.
    $('#d3').prop('checked',false);
</script>
</body>
</html>

8. 文档操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="d1">div
    <p id="d2">div>p</p>
    <span>div>span</span>
    <p>div>p</p>
</div>

<script>
    /*
    js中的文档处理                     jq中的文档处理
    document.createElement(tagName)  $('<tagName>')
    标签对象.appendChild(标签对象)      jq对象.append(包含标签的jq对象)
    */
    let $pEle = $('<p>');
    $pEle.text('你好啊 草莓要不要来几个?');
    $pEle.attr('id', 'd3');
    $('#d1').append($pEle);  // 内部尾部追加
    $pEle.appendTo($('#d1'));

    $('#d1').prepend($pEle);  // 内部头部追加
    $pEle.prependTo($('#d1'));

    $('#d2').after($pEle);  // 放在某个标签后面
    $pEle.insertAfter($('#d1'));

    $('#d1').before($pEle);  // 放在某个标签前面
    $pEle.insertBefore($('#d2'));

    $('#d1').remove(); // 将标签从DOM树中删除

    $('#d1').empty();  // 清空标签内部所有的内容
    $('#d1').html('')  // 等同
</script>
</body>
</html>

9. 总结

# CSS 类操作:
    js中:
        .classList.add()
        .classList.remove()
        .classList.contains()
        .classList.toggle()
    jq中:
        jq对象.addClass(className)
        jq对象.removeClass(className)
        jq对象.hasClass(className)
        jq对象.toggleClass(className)

# CSS 样式操作:
    js中:
        .style.fontSize = '18px'
        .style.color = 'red'
    jq中: 只要返回的是jq对象就可以连续的操作对象中含有的所有方法
        jq对象.css('fontSize', '18px').next().css('color', 'red')

# 位置操作:
    jq对象.offset()  元素左上角到浏览器位置
    jq对象.position()  元素中心到父元素位置
    $(window).scrollTop()   .scrollTop(0)    无值获取, 有值设置
    $(window).scrollLeft()  .scrollLeft(0)

# 尺寸:
    content
        jq对象.height()
        jq对象.width()
    content+padding
        jq对象.innerHeight()
        jq对象.innerWidth()
    content+padding+border
        jq对象.outerHeight()
        jq对象.outerWidth()

# 文本操作:
    js中:
        .innerText   .innerText='文本'
        .innerHTML   .innerHTML='文本+标签'
    jq中:
        jq对象.text()      jq对象.text(文本)  不加获取, 加则设置
        jq对象.html()      jq对象.html(文本+标签)

# 值操作:
    js中:
        非文件 .value  .value=''
        文件:  .files  .files[0]  文件的.value获取本地上传路径
    jq中:
        非文件: jq对象.val()  jq对象.val('')   不加获取, 加则设置
        文件:   $(':file')[0].files[0]  jq中没有获取文件对象操作, 只能先拿到jq对象再转成js对象, 再进行获取文件对象操作

# 属性操作:
    js中:
        .getAttribute(attrName, attrValue)
        .setAttribute(attrName)
        .removeAttribute(attrName)
    jq中:
        获取属性: jq对象.attr(attrName)
        设置属性: jq对象.attr(attrName, attrValue)

        获取操作是否选中的布尔值: jq对象.prop(attrName)  专门针对用户是否选中, 返回布尔值的操作(selected, checked)
        设置布尔值进而让操作选中: jq对象.prop(attrName, boolValue)

# 文档操作:
    js中:
        .appendChild()
        .removeChild()
        .replaceChild()
        .insertBefore()
    jq中:
        内部尾部: jq对象.append($Ele)   $Ele.appendTo(jq对象)
        内部头部: jq对象.prepend($Ele)  $Ele.prependTo(jq对象)
        同级别后: jq对象.after($Ele)    $Ele.inertAfter(jq对象)
        同级别前: jq对象.before($Ele)   $Ele.insetBefore(jq对象)
        直接删除: jq对象.remove()
        内部清空: jq对象.empty()    等同于 .html('')

十二. 事件

1. jQuery绑定事件2种的方式

// 第一种
    $('#d1').click(function () {
            alert('别说话 吻我')
    });
  
// 第二种(功能更加强大 还支持事件委托)
    $('#d2').on('click',function () {
            alert('借我钱买草莓 后面还你')
    })

2. 克隆事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            margin: 0;
        }

        #d1 {
            height: 100px;
            width: 100px;
            background-color: orange;
            border: 1px solid blue;
        }
    </style>
</head>
<body>
<button id="d1">屠龙宝刀,点击就送</button>

<script>
    $('#d1').on('click', function () {
        console.log(this); // this指代是当前被操作的标签对象
        $(this).clone(true).insertAfter($('#d1'));  // clone默认情况下只克隆html和css 不克隆事件
        $(this).clone().insertAfter($('#d1'));  // 括号内加true即可克隆事件
    })
</script>
</body>
</html>

3. 自定义模态框

模态框内部本质就是给标签移除或者添加上hide属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            margin: 0;
        }
        .popup {
            display: block;
            width: 100px;
            height: 100px;
            background-color: red;
            margin: 100px auto;
        }
        .hide {
            display: none;
        }
        .cover {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: rgba(172, 172, 172, .5);
            z-index: 99;
        }
        .model {
            width: 600px;
            height: 400px;
            position: fixed;
            top: 50%;
            left: 50%;
            margin-top: -200px;
            margin-left: -300px;
            background-color: #fff;
            z-index: 100;
            text-align: center;
        }
        h2 {
            margin-top: 100px;
        }
        #d1,#d2 {
            margin: 10px 0;
        }
    </style>
</head>
<body>
<button class="popup">弹出</button>
<div class="cover hide"></div>
<div class="model hide">
    <h2>欢迎登录</h2>
    <label for="d1">
        username: <input type="text" id="d1">
    </label><br>
    <label for="d2">
        password: <input type="password" id="d2">
    </label><br>
    <button class="close">关闭</button>
</div>

<script>
    // $('popup').on('click', function () {
    //     $('cover').removeClass('hide');
    //     $('model').removeClass('hide');
    // })
    $('.popup').click(function () {
        // 方式一:
        /*
        let coverEle = $('.cover')[0];
        let modelEle = $('.model')[0];
        $(coverEle).removeClass('hide');
        $(modelEle).removeClass('hide');
        */

        // 方式二:
        // $('.cover').removeClass('hide');
        // $('.model').removeClass('hide');

        // 方式三:
        $('.cover,.model').removeClass('hide');
    });
    $('.close').on('click', function () {
        $('.cover,.model').addClass('hide');
    })
</script>
</body>
</html>

4. 左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        html,body {
            margin: 0;
            height: 100%;
        }
        .left {
            width: 20%;
            height: 100%;
            background-color: #b0b0b0;
            float: left;
        }
        .title {
            width: 80%;
            font-size: 36px;
            text-align: center;
            margin: 0 auto 20px ;
        }
        .title:hover {
            cursor: pointer;
            color: #ff6700;
        }
        .item {
            border: 2px solid rgba(255, 255, 255, .7);
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div class="left">
    <div class="menu">
        <div class="title">菜单一
            <div class="item">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
        <div class="title">菜单二
            <div class="item">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
        <div class="title">菜单三
            <div class="item">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
    </div>
</div>

<script>
    $(".item").addClass('hide');
    $('.title').on('click', function () {
        // console.log(this);
        $(this).children().toggleClass('hide');
    })
</script>
</body>
</html>

5. 返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .hide {
            display: none;
        }
        #d1 {
            position: fixed;
            background-color: #fff;
            right: 20px;
            bottom: 20px;
            width: 50px;
            height: 50px;
            text-align: center;
            border-radius: 8px 8px;
            color: black;
        }
    </style>
</head>
<body>
<a href="" id="d1"></a>
<div style="height: 800px;background-color: red"></div>
<div style="height: 800px;background-color: greenyellow"></div>
<div style="height: 800px;background-color: blue"></div>
<a href="#d1" class="hide">回到顶部</a>

<script>
    $(window).on('scroll', function () {
        if ($(window).scrollTop() > 200) {
            $('#d1').removeClass('hide');
        } else {
            $('#d1').addClass('hide');
        }
    })
</script>
</body>
</html>

6. 自定义登陆校验

在获取用户的用户名和密码的时候 用户如果没有填写 应该给用户展示提示信息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<P>
    username: <input type="text">
    <span style="color: red"></span>
</P>
<P>
    password: <input type="password">
    <span style="color: red"></span>
</P>
<button id="d1">提交</button>

<script>
    $('#d1').on('click', function () {
        if (!$(':text').val()) {
            $(':text').next().text('账号不能为空!');
        }
        if (!$(':password').val()) {
            $(':password').next().text('密码不能为空!');
        }
    });

    // $(':text').on('focus', function () {
    //     $(this).next().text('');
    // });
    // $(':password').on('focus', function () {
    //     $(this).next().text('');
    // });

    // 优化: this可以灵活的获取到当前操作的标签对象
     $('input').on('focus', function () {
        $(this).next().text('');
    });
</script>
</body>
</html>

7. input实时监控

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="d1">

<script>
    $('#d1').on('input', function () {
        console.log(this.value);
    });
</script>
</body>
</html>

8. hover事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p id="d1">父爱武林风福啊玩你额官方!</p>

<script>
    // $('#d1').on('hover', function () {
    //     alert('来宾一位');  // 鼠标悬浮 + 鼠标移开
    // });


    $('#d1').hover(function () {
        alert('我来了');   // 悬浮
    }, function () {
        alert('我走了');   // 移开
    })
</script>
</body>
</html>

9. 键盘按键按下事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<script>
    // 第二种绑定事件的方式无效: 具体为什么, 我也不知道
    // $('#d1').on('keydown', function (event) {
    //     console.log(event.keyCode);
    //     // if (event.keyCode === 13) {
    //     //     alert('你按了回车键!');
    //     // }
    // });

    $(window).keydown(function (event) {
        console.log(event.keyCode);
        if (event.keyCode === 13) {
            alert('你按了回车键!')
        }
    })
</script>
</body>
</html>

10. 阻止后续事件执行2种方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="">
    <span id="d1" style="color: red"></span>
    <input type="submit" id="d2" value="提 交">
</form>

<script>
    /*
    return false
    event.preventDefault()
    */
    $("#d2").click(function (event) {
        // 实现方式一:  
        // $(this).prev().text('你看的见我吗?');

        // 实现方式二:
        $('#d1').text('你看的见我吗?');

        // 阻止后续事件执行方式一:  JQ中的阻止
        // return event.preventDefault();

        // 阻止后续事件执行方式二:  原生JS中的阻止
        return false;
    });
</script>
</body>
</html>

11. 阻止事件冒泡的2种方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .box1 {
            width: 400px;
            height: 400px;
            background-color: #ff6700;
            text-align: center;
            position: relative;
        }

        .box2 {
            width: 200px;
            height: 200px;
            background-color: blue;
            text-align: center;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }
    </style>
</head>
<body>
<div class="box1">
    box1
    <div class="box2">box2</div>
</div>


<script>
    /*
    return false
    event.stopPropagation()
    */
    $(".box1").click(function () {
        alert('box1');
    });
    $('.box2').click(function (event) {
        alert('box2');
        // 阻止事件冒泡的方式一: JQ中的阻止
        // return false;

        // 阻止事件冒泡的方式二: 原生JS中的阻止
        event.stopPropagation();
    });
</script>
</body>
</html>

没有阻止事件冒泡之前

1

阻止事件冒泡之后

![](01 jQuery.assets/1402974-20200621213719683-1979968661.gif)

12. 利用jq开始事件的第二种on的方式开启事件委托

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button>是兄弟,就来砍我!!!</button>

<script>
    /*
    $('body').on('click', 'button', function(){})
    */

    /*
    $('<button>').text('我来砍你来了!').insertAfter($('button'));
    */
    // 给页面上所有的button标签绑定点击事件. 无法影响到动态创建的标签
    // $('button').click(function () {
    //     alert('123');
    // });

    // 事件委托
    $('body').on('click', 'button', function () {
        alert('123');  // 在指定的范围内 将事件委托给某个标签 无论该标签是事先写好的还是后面动态创建的
    })
</script>
</body>
</html>

13. 总结

# 开启事件的2种方式:
    $('#d1').click(function () {})
    $('#d1').on('click', function() {})  功能更加强大 还支持事件委托

# 克隆事件
    this代指的是被操作的标签对象
    .clone() 不指定. 只复制源对象html和css, 不复制事件
    .clone(true) 指定. 既可以复制源对象对象html和css, 还可以复制源对象绑定的事件

# 模态框:
   利用click点击事件来为标签对象增添或删除类属性.

# 左侧菜单栏:
    利用click点击事件来为菜单栏中的子标签动态的增添或删除类属性.

# 返回顶部:
    在window对象基础之上利用提供的scroll事件, 以及位置操作$(window).scrollTop()的取值, 在一定的滚动条时显示, 返回顶部的区域.

# 自定义登录效验:
    利用提交触发点击click事件, 获取input框中的值是否为空, 如果为空则在后面将提示内容显示. 同时, 再利用focus获取其焦点事件, 当获取焦点时, 后面的提示内容要清空.

# input框时时监控:
    利用input事件可以时时获取value值

# hover事件:
    绑定一个函数: 鼠标悬浮+鼠标移开
    绑定二个函数: 第一个函数表示鼠标悬浮, 第二个函数标识鼠标移开

# 键盘按下事件:
    利用keydown事件, 在函数中定义event参数, 通过event.keyCode动态的获取用户键盘输入内容与ASCII对于的十进制数字
    
# 阻止后续事件执行2种方式:
    第一种: return false
    第二中: 设置参数event, 再return event.preventDefault()

# 阻止事件冒泡的2种方式:
    第一种: return false
    第二种:   设置参数event, 再return event.stopPropagation()

# 利用jq开始事件的第二种on的方式开启事件委托:
     作用: 开启事件委托可以对动态添加的标签起作用
     $('开启事件委托的区域').on('事件', '需要委托的事件', function() {})    

十三. jq书写代码的3种位置

"""js中等待页面加载完毕"""
# 等待页面加载完毕再执行代码
window.onload = function(){
  // js代码
}

"""jQuery中等待页面加载完毕"""
# 第一种
$(document).ready(function(){
  // js代码
})
# 第二种
$(function(){
  // js代码
})
# 第三种
"""直接写在body内部最下方"""

十四. 动画效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        #d1 {
            height: 1000px;
            width: 400px;
            background-color: red;

        }
    </style>
</head>
<body>
    <div id="d1"></div>

<script>
    /*
    .hide(msec)             // 隐藏
    .show(msec)             // 显示
    .slideUp(msec)          // 向上卷起
    .slideDown(msec)        // 向下展开
    .fadeOut(msec)          // 淡出
    .fadeIn(msec)           // 淡入
    .fadeTo(msec, opacity)  // 透明度渐变 更改透明度值来产生淡入或者淡出效果
    */
    /*
    $('#d1').hide(5000);
    $('#d1').show(5000);
    $('#d1').slideUp(5000);
    $('#d1').slideDown(5000);
    $('#d1').fadeOut(5000);
    $('#d1').fadeIn(5000);
    $('#d1').fadeTo(5000, 0.5);
    */
</script>
</body>
</html>

十五. jq实现类始于js中数组对象方法.forEach()或者.map()的.each方法: 2种.each方法实现方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="d1" username="jason">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>

<script>
    /*
    $('div').each(function (index, obj) {});
    $.each($('li'), function (index, obj) {});
    */

    // 第一种写法:
    $('div').each(function (index) {  // 指定一个参数返回索引
        console.log(index);
    });

    $(['aaa', 'bbb', 'ccc']).each(function (index, obj) {  // 也可以指定2个参数, 第二个参数返回遍历对象的索引对应的值.
        console.log(index, obj);
    });

    // 第二种写法:
    $.each($('div'), function (index, obj) {
        console.log(index, obj);  // obj返回了标签对象
    });
</script>
</body>
</html>

十六. jq实现隐藏的标签属性

/*
$('div').data('info', 'value');
$('div').first().data('info');
$('div').last().removeData('info')
*/

$('div').data('info', '回来吧,我原谅你了!');  // 设置让标签帮我们存储数据 并且用户肉眼看不见
$('div').first().data('info');      // 查看
$('div').last().data('info');
$('div').last().removeData('info')  // 移除
$('div').last().data('info');

总结

# jq书写代码的3种位置:
    第一二重: head中, 需要预加载
        $(document).ready(function () {})
        $(function () {})

    第三种: body底部可以直接书写

# 动画效果:  最后display会等于none
    隐藏: jq对象.hide(mesc)
    展现: jq对象.show(mesc)
    上卷: jq对象.slideUp(mesc)
    下展: jq对象.slideDown(mesc)
    淡出: jq对象.fadeIn(mesc)
    淡入: jq对象.fadeOut(mesc)
    透明度渐变: jq对象.fadeTo(mesc, opacity)

# jq实现类始于js中数组对象方法.forEach()或者.map()的.each方法:  2种.each方法实现方式
    第一种:
        $('div').each(function (index, obj) {})
        $([1, 2, 3]).each(function (index, obj) {})
    第二种:
        $.($('div'), function (index, obj) {})
        $.([1, 2, 3], function (index, obj) {})
    提示: 2者对任意类型的对象, 都可以进行遍历, 使用each就替代掉了for循环遍历取值
    参数: index表示获取到的标签对象obj索引位置. obj就是索引对象. 其中index,和obj参数都是可选的.

# jq实现隐藏的标签属性:
    设置: .data(attrName, attrValue)
    获取: .data(attrName)
    删除: .removeData(attrName)

十七. js里定义的$ 和jquery的$冲突解决

// 1. 解决多个库变量名冲突的方法: 将jQuery的$变量控制权交给index.js
jQuery.noConflict(); // Conflict,中文:冲突,读音:[/ˈkɒnflɪkt/]
console.log($);

// 2. JQuery使用自制性函数: 将jQuery对象当作形参赋值给$符
(function($) {
	$(document).ready(function() {
		console.log($);
		// 使用id选择器: 使用jquery下的css方法,为box文本设置红色字体
		$('#box').css('color','red');
	});
})(jQuery);
posted @ 2020-05-20 01:29  给你加马桶唱疏通  阅读(249)  评论(0编辑  收藏  举报