jQuery 框架

发布时间 2023-11-09 11:50:22作者: 宁采臣open

jQuery 框架

一. 概述

jQuery 是一个 JavaScript 库。

jQuery 极大地简化了 JavaScript 编程。

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

兼容多个浏览器的 你在使用jQuery的时候就不需要考虑浏览器兼容问题

jQuery的宗旨
	write less do more
	让你用更少的代码完成更多的事情

复习
	python导入模块发生了哪些事?
		导入模块其实需要消耗资源
	jQuery在使用的时候也需要导入
		但是它的文件非常的小(几十KB) 基本不影响网络速度

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

版本介绍

jQuery文件下载
	压缩  		容量更小
	未压缩
"""
# jQuery在使用之前 一定要确保已经导入了


帮助文档:https://m.runoob.com/jquery/jquery-install.html

二. jQuery 安装引用

2.1 安装

#01 安装地址
https://jquery.com/download/

这里使用的是 3.7.1
https://code.jquery.com/jquery-3.7.1.min.js



image-20231107133333763

2.2 本地导入使用

#01 本地文件直接导入 src=""
<head>
    <script src="jQuery-3.7.1.js"></script>
</head>

#02 pycharm 提供的自动初始化默认
<script src="jQuery-3.7.1.js"></script>

注意该两种方式,本地必须已经下载了 jQuery-3.7.1.js 文件,而且在统计目录

image-20231107134316382

2.3 jQuery CDN引入

"""
如果您不希望下载并存放 jQuery,那么也可以通过 CDN(内容分发网络) 引用它。

Staticfile CDN、百度、又拍云、新浪、谷歌和微软的服务器都存有 jQuery 。

如果你的站点用户是国内的,建议使用百度、又拍云、新浪等国内CDN地址,如果你站点用户是国外的可以使用谷歌和微软。
"""

#01 cdn引入
https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


三. jQuery基本语法

#01 jQuery基本语法
	jQuery(选择器).action操作()
  
  秉持着jQuery的宗旨 jQuery简写	$
  
  jQuery()  === $()

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

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

image-20231107140112844

四. 查找标签

4.1 基本选择器

#01 id选择器
$('#d1');
ce.fn.init [div#d1]0: div#d1length: 1[[Prototype]]: Object(0)
            
#02  class 选择器
$('.c1');
ce.fn.init [prevObject: ce.fn.init(1)]
            
#03 标签选择器
$('span');
ce.fn.init(2) [span, span, prevObject: ce.fn.init(1)]0:
            span1: spanlength: 
            2prevObject: ce.fn.init 
            [document][[Prototype]]: Object(0)
            
            
"""
// 上述得到的为 jQuery对象
// 可以转为标签对象,方式如下
"""

#04  jQuery对象转为标签对象,取索引0       
$('#d1')[0]
<div id=​"d1">​…​</div>​

#05 标签对象转为 jQuery对象 $('标签对象')       
$(document.getElementById('d1'))
ce.fn.init [div#d1]0: div#d1length: 1[[Prototype]]: Object(0)
            
            
     

image-20231107141929385

4.2 组合选择器/分组与嵌套



//div包含c1类的标签
$('div.c1')
ce.fn.init [div.c1, prevObject: ce.fn.init(1)]

//div标签包含 idd1的标签
$('div#d1')
ce.fn.init [div#d1, prevObject: ce.fn.init(1)]

// 找出ID 类 标签并列
$('#d1,.c1,p')
ce.fn.init(4) [div#d1, p, div.c1, p, prevObject: ce.fn.init(1)]

// 后代,div下面所有的span
$('div span')
ce.fn.init(2) [span, span, prevObject: ce.fn.init(1)]

// 儿子,只有div下面的span 不递归查找
$('div>span');
ce.fn.init [span, prevObject: ce.fn.init(1)]

 // 毗邻 div 邻近的span 注意只能找div 下方临近的第一个标签是否是 span
$('div+span')
ce.fn.init [span, prevObject: ce.fn.init(1)]

// 弟弟 跟div同级别
$('div~span')
ce.fn.init(3) [span, span, span, prevObject: ce.fn.init(1)]

image-20231107144219422

4.3 基本筛选器

// 大儿子 找出第一个值
$('ul li:first');

// 小儿子 找出最后一个值
$('ul li:last');

// 指定索引取值
$('ul li:eq(3)');

// 取偶数索引的值 零包含在内
$('ul li:even')

// 取奇数索引的值 
$('ul li:odd')

// 大于索引的
$('ul li:gt(2)')

// 小于索引的
$('ul li:lt(2)')

// 排除满足条件的
$('ul li:not("#d1")');

// 选取出包含一个或者多个标签在内的标签
$('div:has("p")')


4.4 属性选择器

// 属性是 username
$('[username]')

// 属性是 username = zhang
$('[username="zhang"]')

// 属性是 username = fu 并且是p标签的
$('p[username="fu"]')

// 内部的标签一样操作
$('[type]')

$('[type="text"]')


  • 代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jQuery-3.7.1.js"></script>
</head>
<body>
<input type="text" username="zhang">
<input type="text" username="yu">
<p username="fu"></p>

</body>
</html>

4.5 表单筛选器

// 找出表单 from类型是 text password
$('input[type="text"]');
$('input[type="password"]');

// 针对表单 from类型 简写 等同上方两个
$(':text'); 
$(':password');   


:text
:password
:file
:radio
:checkbox
:submit
:reset
:button
...

表单对象属性
:enabled
:disabled
:checked
:selected


"""特殊情况"""
// 找类型是 checked 它会将checked和selected都拿到
$(':checked');

// 它不会 只拿selected
$(':selected')  

// 找类型是 checked 加限制条件
$('input:checked');


  • 代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jQuery-3.7.1.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="222" checked> 222
    <input type="checkbox" value="333"> 333
    <select name="" id="">
        <option value="">111</option>
        <option value="">222</option>
        <option value="" selected>333</option>

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

</form>
</body>
</html>

4.6 筛选器方法



// 同级别下一个
$('#d1').next();


// 同级别下方所有标签
$('#d1').nextAll();

// 同级别下所有标签 到特定标签结束
$('#d1').nextUntil('.c1');

// 同级别上一个
$('.c1').prev();

// 同级别上所有标签
$('.c1').prevAll();

// 同级别上所有标签 到指定标签结束 (不包含指定的标签)
$('.c1').prevUntil('#d1');


// 第一级父标签
$('#d3').parent;
$('#d3').parent().parent();


// 往上找所有的父标签 截止到html标签 包含html
$('#d3').parents()

// 往上找所有的父标签 截止到指定标签
$('#d3').parentsUntil('body')


// 儿子 同级别下 所有
$('#d2').children();

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


---
// find从某个区域内筛选出想要的标签          
$('div').find('p')  // 等于 $('div p')


// 特定标签的第一个 (span 有多个 取第一个)
$('div span').first();

// 特定标签的最后一个  (span 有多个 取最后一个)
$('div span').last();

// 特定标签 不包含,排除 (span 有多个 排除id是 id3的)
$('div span').not('#d3');


  • 代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jQuery-3.7.1.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>
</body>
</html>

五. 练习题

5.1 答案

// 1.找到本页面中id是i1的标签
$('#i1');

// 2.找到本页面中所有的h2标签
$('h2');

// 3.找到本页面中所有的input标签
$('input');

// 4.找到本页面所有样式类中有c1的标签
$('.c1');

// 5.找到本页面所有样式类中有btn-default的标签
$('.btn-default');


// 6.找到本页面所有样式类中有c1的标签和所有h2标签
$('.c1,h2');


// 7.找到本页面所有样式类中有c1的标签和id是p3的标签
$('.c1,#p3');

// 8.找到本页面所有样式类中有c1的标签和所有样式类中有btn的标签
$('.c1,.btn');

// 9.找到本页面中form标签中的所有input标签
$('form').find('input');

// 10.找到本页面中被包裹在label标签内的input标签
$('label').find('input');
$('label input');


// 11.找到本页面中紧挨在label标签后面的input标签
$('label+input');


// 12.找到本页面中id为p2的标签后面所有和它同级的li标签
$('#p2~li');


// 13.找到id值为f1的标签内部的第一个input标签
$('#f1 input').first();


// 14.找到id值为my-checkbox的标签内部最后一个input标签
$('#my-checkbox input').last();


// 15.找到id值为my-checkbox的标签内部没有被选中的那个input标签
$('#my-checkbox input[checked!="checked"]');


// 16.找到所有含有input标签的label标签
$('label').has('input');


5.2 代码

<!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>

六. 操作标签

6.1 样式类操作

"""
js版本														jQuery版本
classList.add()										addClass()			增加
classList.remove()								removeClass()		移除
classList.contains()							hasClass()			判断是否包含
classList.toggle()								toggleClass()		有则添加 无责移除
"""

// 获取所有的类
$('#d1');
k.fn.init [div#d1.c1.c2.c3]
           
// 移除c1
$('#d1').removeClass('c1');
k.fn.init [div#d1.c2.c3]
           
// 添加c1类
$('#d1').addClass('c1');
k.fn.init [div#d1.c2.c3.c1]
           
// 有侧移除 无则添加
$('#d1').toggleClass('c1');
k.fn.init [div#d1.c2.c3]
           
// 有侧移除 无则添加
$('#d1').toggleClass('c1');
k.fn.init [div#d1.c2.c3.c1]
           
// 判断c2是否存在
$('#d1').hasClass('c2');
true
// 判断c22是否存在
$('#d1').hasClass('c22');
false


6.2 css操作

#01 实现一行代码 改变3个p标签为不同颜色
$('p').first().css('color','red').next().css('color','green').next().css('color','red');

这是jQuery返回的是个对象 所以可以使用对象内的方法

# jQuery的链式操作 使用jQuery可以做到一行代码操作很多标签
# jQuery对象调用jQuery方法之后返回的还是当前jQuery对象 也就可以继续调用其他方法

class MyClass(object):
    def func1(self):
        print('func1')
        return self

    def func2(self):
        print('func2')
        return self


obj = MyClass()
obj.func1().func2()

python返回对象 也可以做到链路操作


6.3 位置操作

##位置操作
#01 相对于浏览器窗口
$('p').offset();
{top: 215.9943084716797, left: 200}

#02 相对于父标签
$('p').position();
{top: 199.9943084716797, left: 200}


#03 上下获取/设置当前移动位置
1)获取当前位置
$(window).scrollTop()
0
2)获取当前位置
$(window).scrollTop()
3264
3)设置当前位置 括号内有值代表设置
$(window).scrollTop(1555)

#04 左右获取/设置当前移动位置
$(window).scrollLeft()
$(window).scrollLeft(123)

6.4 尺寸操作

image-20231107175436938

# 尺寸
#01 文本尺寸
1) 高度
$('p').height();
22.7273
2) 宽度
$('p').width(); 
1089.46


#02 文本+padding 尺寸
$('p').innerHeight();
42.7273
$('p').innerWidth();
1119.46


#03 文本+padding+border 尺寸
$('p').outerWidth();
1119.46
$('p').outerHeight();
42.7273

6.5 文本操作

"""
操作标签内部文本
js											jQuery
innerText								text()  括号内不加参数就是获取加了就是设置
innerHTML								html()
"""


// 获取文本信息
$('div').text();
'世界这么大 还是遇见你'

// 获取文本信息加标签
$('div').html();
'<p>世界这么大 还是遇见你</p>'


// 设置文本信息
$('div').text('世界你好');

// 设置标签加文本信息
$('div').html('<h1>世界你好</h1>');

6.6 获取值操作

"""
js													jQuery
.value											.val()
"""


// 01 获取input用户输入的内容
$('#d1').val();


// 02 设置input用户输入的内容,加括号代表获取
$('#d1').val('付付你好');


// 03 获取文件
$('#d2')[0].files[0];

注意:这里先转为js原生对象 然后通过files方法取值

image-20231108092603503

6.7 属性操作

"""
js中																jQuery
setAttribute()											attr(name,value)
getAttribute()											attr(name)
removeAttribute()										removeAttr(name)
																		$('#d2').prop('checked')
在用变量存储对象的时候 js中推荐使用	
	XXXEle			标签对象
jQuery中推荐使用
	$XXXEle			jQuery对象
	
修改设置自定义属性

对于标签上有的能够看到的属性和自定义属性用attr
对于返回布尔值比如checkbox radio option是否被选中用prop
"""


#01 获取标签对象 并赋值给变量
let $pEle = $('p');
undefined

#02 获取id属性
$pEle.attr('id');
'd1'

#03 设置id属性
$pEle.attr('id','d5');
$pEle.attr('id');
'd5'

#04 获取类属性
$pEle.attr('class');
undefined

#05 设置类属性
$pEle.attr('class','c1'); 
$pEle.attr('class');
'c1'

#06 设置自定义属性
$pEle.attr('useranme','fufu'); 
$pEle.attr('useranme'); 
'fufu'


----针对用户选择框 checkbox radio option  查看是否被选中用prop----

#01 查看是否被用户选中 返回 false true
1)查看返回结果
$('#d2').prop('checked')
false

2)两个值是设置
$('#d2').prop('checked','true')
k.fn.init [input#d2]

3)检查
$('#d2').prop('checked')
true

           

6.8 文档处理

"""
js																		jQuery
createElement('p')										$('<p>')		创建标签
appendChild()													append()		添加标签

"""


#01 创建p标签
let $pEle = $('<p>');
undefined

#02 添加文本
$pEle.text('你好啊 要草莓吗'); 

#03 添加属性
$pEle.attr('id','p1');

#04 内部尾部追加	两种写法效果一样,会在 d2标签的下面添加该标签
$('#d2').append($pEle)
$pEle.appendTo($('#d2'));

#05 头部添加 两种写法效果一样 会在标签上面
$('#d1').prepend($pEle);
$pEle.prependTo($('#d2'))

#06 插入指定标签下面第一个 两种写法一样
$pEle.insertAfter($('#d1'));
$('#d2').after($pEle);

#07 插入指定标签上面第一个 两种写法一样
$('#d1').before($pEle)
$pEle.insertBefore($('#d2'))


#08 删除标签
$('#d1').remove();

#09 清空标签内部所有内容 不包含标签本身
$('#d1').empty()

七. 事件相关

7.1 绑定事件的方式

"""click 点击事件"""

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button id="d1">点我</button>
<button id="d2">再点下</button>

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

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


7.2 克隆事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<style>
  #d1 {
    border: 5px yellow solid;
    height: 100px;
    width: 100px;
    background-color: gold;
  }

</style>

<body>
<button id="d1">点击就送屠龙宝刀</button>

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

</script>

</body>
</html>

7.3 自定义模态框

"""
label 标签
    定义: <label>标签为 input 元素定义标注(标记)
    说明: 1. label元素不会向用户呈现任何特殊效果
             2. <label>标签的for属性值应当与相关元素的id属性值相同
"""

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

<style>
    .cover {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background-color: darkgrey;
        z-index: 999;
    }

    .modal {
        width: 600px;
        height: 400px;
        background-color: white;
        position: fixed;
        left: 50%;
        top: 50%;
        margin-left: -300px;
        margin-top: -200px;
        z-index: 1000;
    }

    .hide {
        display: none;
    }
</style>
<body>
<input type="button" value="弹出" id="d1">
<div id="d2" class="cover hide"></div>
<div class="modal hide">
    <label for="i1">姓名</label>
    <input  id="i1" type="text">
    <label for="i2">密码</label>
    <input id="i2" type="text">
    <input type="button" id="i3" value="关闭">
</div>

<script>
    // 01 绑定点击事件 点击弹出后 移除hide属性(默认展示)
    $('#d1').on('click',function (){
        // 1.1 获取标签对象
        var corverEle = $('.cover')[0]
        var modalEle = $('.modal')[0]

        // 转为Query对象 并移除默认展示
        $(corverEle).removeClass('hide')
        $(modalEle).removeClass('hide')
    })
    // 02 点击关闭时 添加 hide属性
    $('#i3').on('click',function (){
        // 1.1 获取标签对象
        var corverEle = $('.cover')[0]
        var modalEle = $('.modal')[0]

        // 转为Query对象 并添加默认展示类
        $(corverEle).addClass('hide')
        $(modalEle).addClass('hide')

    })

</script>

</body>
</html>


7.4 左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<style>
    .left {
        float: left;
        position: fixed;
        width: 30%;
        height: 100%;
        background-color: lightgoldenrodyellow;
    }
    .title {
        font-size: 36px;
        text-align: center;
        color: black;
    }
    .items {
        border: 2px yellowgreen solid;
        font-size: 24px;
    }
    .hide {
        display: none;
    }

</style>


<body>

<div class="left">
    <div class="men">
        <div class="title">菜单一
            <div class="items">111</div>
            <div class="items">222</div>
            <div class="items">333</div>
        </div>
        <div class="title">菜单二
            <div class="items">111</div>
            <div class="items">222</div>
            <div class="items">333</div>
        </div>
        <div class="title">菜单三
            <div class="items">111</div>
            <div class="items">222</div>
            <div class="items">333</div>
        </div>
    </div>
</div>

<script>
    $('.title').click(function (){
        //01 先给所有items 加上hide
        $('.items').addClass('hide')
        //02 然后将被点击标签内部的 hide移除
        $(this).children().removeClass('hide')
    })

</script>

</body>
</html>

7.5 返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<style>
    .hide {
        display: none;

    }

    #d1 {
        border: #111111 solid 5px;
        position: fixed;
        right: 20px;
        bottom: 20px;
        height: 20px;
        width: 70px;
    }


</style>

<body>
<div style="height: 500px;background-color: red"></div>
<div style="height: 500px;background-color: greenyellow"></div>
<div style="height: 500px;background-color: blue"></div>
<a id="d1" href="" class="hide">返回顶部</a>

<script>
    // 屏幕滚动事件
    $(window).scroll(function (){
        //判断屏幕滚动超过300 则移除 hide 展示回到顶部
        if($(window).scrollTop() > 300){
            $('#d1').removeClass('hide')
        }
    })
    // 点击事件,点击回到顶部后 回到顶部
    $('d1').click(function (){
        $(window).scrollTop(0)
    })

</script>

</body>
</html>

7.6 自定义登入校验

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

<body>
<p>请输入账户:
    <input type="text" id="d1">
    <span style="color: red"></span>

</p>
<p>请输入密码:
    <input type="password" id="d2">
    <span style="color: red"></span>
</p>
<button id="d3">提交</button>

<script>
    // 01 绑定点击事件 用户提交判断输入是否是空
    let $user = $('#d1')
    let $pass = $('#d2')
    $('#d3').click(function () {
        // 获取用户输入
        let user = $user.val()
        let pass = $pass.val()
        if (!user) {
            $user.next().text("账户不能为空")
        }
        if (!pass) {
            $pass.next().text("密码不能为空")
        }

    })

    // 02 当用户重新输入时候 focus 聚焦点 取消该文本提示
    $('input').focus(function () {
        // 找出input 下面的span便签 清空提示
        $('input').next().text('')
    })


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


7.7 input实时监控

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>k</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>
<input type="text" id="d1">

<script>
    // 绑定input事件 获取输入内容
    $('#d1').on('input',function () {
        console.log(this.value)
    })
</script>
</body>
</html>

image-20231108145132438

7.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.4.1/jquery.min.js"></script>
</head>
<body>
<span id="d1">不要把鼠标移动过来 有惊喜</span>

<script>
  // 绑定hover 鼠标悬浮事件
  $('#d1').hover(function (){
    alert('你还真点啊,上当了把')
  },
  function (){
    alert('别走啊 我开玩笑的')
  }
  )

</script>

</body>
</html>

7.9 键盘按键按下事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
    $(window).keydown(function (event) {
        console.log(event.keyCode)
        if (event.keyCode === 16){
            alert('你按了shift键')
        }
    })
</script>
</body>
</html>

7.10 阻止后续事件的执行

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


<input id="d2" type="submit">
<p><span id="d1" style="color: red" ></span></p>

<script>
  // 点击input按钮 往span标签添加一句话
  $('#d2').click(function (){
    $('#d1').text('宝贝 你能看见我吗')
     // 阻止标签后续事件的执行 方式1
     // return false
     // 阻止标签后续事件的执行 方式2 需要传参数
     // e.preventDefault()  
    return false
  })

</script>

</body>
</html>



7.11 阻止事件冒泡

#01 点击子标签绑定事件后  子标签执行完毕后会父标签询问 父标签如果也绑定该事件 同样会执行

<script>
        $('#d1').click(function () {
            alert('div')
        })
        $('#d2').click(function () {
            alert('p')
        })
        $('#d3').click(function (e) {
            alert('span')
            // 阻止事件冒泡的方式1
            // return false
            // 阻止事件冒泡的方式2
            // e.stopPropagation()
        })
</script>

7.12 事件委托

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

<script>
    // 给页面上所有的button标签绑定点击事件
    // $('button').click(function () {  // 无法影响到动态创建的标签
    //     alert(123)
    // })

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




7.13 页面加载

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

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

7.14 动画效果

// 动画效果 5秒后展示或者隐藏
$('#d1').hide(5000)

$('#d1').show(5000)

$('#d1').slideUp(5000)

$('#d1').slideDown(5000)

$('#d1').fadeOut(5000)

$('#d1').fadeIn(5000)

$('#d1').fadeTo(5000,0.4)
  



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

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

八. 标签 循环 存储数据

  • each 循环
  • data 存储数据
# each()
# 第一种方式
// each 循环
$('div')
k.fn.init(10) [div, div, div, div, div, div, div, div, div, div, prevObject: k.fn.init(1)]
// each 循环 放一个参数取索引
$('div').each(function (index) {console.log(index)
    
})
VM195:2 0
VM195:2 1
VM195:2 2
VM195:2 3
VM195:2 4
VM195:2 5
VM195:2 6
VM195:2 7
VM195:2 8
VM195:2 9
k.fn.init(10) [div, div, div, div, div, div, div, div, div, div, prevObject: k.fn.init(1)]

// each 放两个参数是 索引和值
$('div').each(function (index,obj) {console.log(index,obj)
    
})
VM226:2 0 <div>​1​</div>​
VM226:2 1 <div>​2​</div>​
VM226:2 2 <div>​3​</div>​
VM226:2 3 <div>​4​</div>​
VM226:2 4 <div>​5​</div>​
VM226:2 5 <div>​6​</div>​
VM226:2 6 <div>​7​</div>​
VM226:2 7 <div>​8​</div>​
VM226:2 8 <div>​9​</div>​
VM226:2 9 <div>​10​</div>​
k.fn.init(10) [div, div, div, div, div, div, div, div, div, div, prevObject: k.fn.init(1)]

# 第二种方式
$.each([111,222,333],function(index,obj){console.log(index,obj)})
VM484:1 0 111
VM484:1 1 222
VM484:1 2 333
(3) [111, 222, 333]
"""
有了each之后 就无需自己写for循环了 用它更加的方便
"""


# data()
"""
能够让标签帮我们存储数据 并且用户肉眼看不见
"""

#01 给所有的标签存储数据
$('div').data('info','回来吧,我原谅你了!')
w.fn.init(10) [div#d1, div, div, div, div, div, div, div, div, div, prevObject: w.fn.init(1)]
        
#02 查询第一个标签内容               
$('div').first().data('info')
"回来吧,我原谅你了!"
$('div').last().data('info')
"回来吧,我原谅你了!"
               
$('div').first().data('xxx')
undefined
               
#03 删除某个便签属性内容               
$('div').first().removeData('info')
w.fn.init [div#d1, prevObject: w.fn.init(10)]
           
$('div').first().data('info')
undefined
$('div').last().data('info')
"回来吧,我原谅你了!"