zoukankan      html  css  js  c++  java
  • jQuery

    jQuery

    1 jQuery简介

    1. jQuery是一个轻量级的、兼容多浏览器的JavaScript库。
    2. jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。它的宗旨就是:“Write less, do more.“
    3. jQuery内部封装了原生的js代码(还额外添加了很多的功能)
      能够让你通过书写更少的代码 完成js操作
      它类似于python里面的模块 (python中的模块在前端叫 “类库”)
    4. 兼容多个浏览器的 你在使用jQuery的时候就不需要考虑浏览器兼容问题

    2 jQuery的宗旨

    ·

    write less do more

    2 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插件做出来的效果很炫,并且可以根据自己需要去改写和封装插件,简单实用。

    3 jQuery的导入

    jQuery文件下载
    压缩版  			容量更小
    未压缩版
    
    ·
    
    将https://code.jquery.com/jquery-3.5.1.min.js网址内的文本复制到本地txt文件中,改后缀名为js
    
    jQuery在使用之前 一定要确保已经导入了
    
    # 1 文件下载到了本地 如何解决多个文件反复书写引入语句的代码
    	可以借助于pycharm自动初始化代码功能完成自动添加
      	配置
        	编辑
          	file and code template
    
      
    # 2 直接引入jQuery提供的CDN服务(基于网络直接请求加载)
    	CDN:内容分发网络
      	CDN有免费的也有收费的
        前端免费的cdn网站:
          	bootcdn
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      """你的计算机必须要有网络"""
      
      
    
    
    # jQuery与js代码对比
    	eg:将p标签内部的文本颜色改为红色
       	// 原生js代码操作标签
    		let pEle = document.getElementById('d1')
    		pEle.style.color = 'red'
    
    		// jQuery操作标签
    		$('p').css('color','blue')
    

    4 jQuery基本语法

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

    5 选择器与筛选器

    5.1 基本选择器

    // id选择器
    $('#d1')
               
               
    // class选择器
    $('.c1')
               
               
    // 标签选择器
    $('span')
    
    
    //jQuery的选择器选择到的是jQuery对象,而不是标签对象
    //jQuery对象内部类似于数组内放标签对象的形式
    
    
    
    """jQuery对象与标签对象	一定要区分开"""
    
    
    // jQuery对象如何变成标签对象
    
    $('#d1')[0]
    
    
    // 标签对象如何转jQuery对象
    
    $(document.getElementById('d1'))
    
    

    5.2 组合选择器(分组与嵌套)

    $('div')
    
    //div下的有c1类的标签,放入jQuery对象
    $('div.c1')
    
    //div下的ID为d1的标签,放入jQuery对象
    $('div#d1')
    
    //所有的标签,放入jQuery对象
    $('*')
    w.fn.init(19) [html, head, meta, title, meta, link, script, script, body, span, span, div#d1, span, p#d2, span, span, div.c1, span, span, prevObject: w.fn.init(1)]
    
    //ID为d1的标签+类为c1的标签+p标签 放入jQuery对象
    $('#d1,.c1,p')  # 并列+混用
    
    
    $('div span')  # 后代
    
                  
    $('div>span')  # 儿子
    
                  
    $('div+span')  # 毗邻
    
                  
    $('div~span')  # 弟弟
    
    

    5.3 基本筛选器

    //ul下的所有li标签
    $('ul li')
    
    //ul下的第一个li标签
    $('ul li:first')  # 大儿子 
    
    //ul下的最后一个li标签
    $('ul li:last')  # 小儿子
    
    
    //ul下的索引为2的li标签(第三个)
    $('ul li:eq(2)')		# 放索引
    
     //ul下的索引为偶数的li标签(第1,3,5,7,9个)              
    $('ul li:even')  # 偶数索引 0包含在内
    
    
    //ul下的索引为奇数的li标签(第2,4,6,8,10个)            
    $('ul li:odd')  # 奇数索引
    
    
    //ul下的索引为大于2的li标签
    $('ul li:gt(2)')  # 大于索引
    
    
    //ul下的索引为小于2的li标签
    $('ul li:lt(2)')  # 小于索引
    
    
    //ul下的ID不为d1的li标签
    $('ul li:not("#d1")')  # 移除满足条件的标签
    
    
    //所有div标签
    $('div')
    
    
    //含有p标签的div标签
    $('div:has("p")')  # 选取出包含一个或多个标签在内的标签
    

    5.4 属性选择器

    //含有username属性的标签,放入jQuery对象
    $('[username]')
    
    //含有username属性且值为jason的标签,放入jQuery对象
    $('[username="jason"]')
    
    //含有type属性的标签,放入jQuery对象
    $('[type]')
    
    //含有type属性且值为text的标签,放入jQuery对象
    $('[type="text"]')
    

    5.5 表单筛选器

    $('input[type="text"]')
    
    $(':text')  # 等价于上面的
    
    
    
    $('input[type="password"]')
    
    $(':password')  # 等价于上面的
    
    
    
    
    # 其他的方法
    :text
    :password
    :file
    :radio
    :checkbox
    :submit
    :reset
    :button
    ...
    
    
    表单对象属性
    :enabled
    :disabled
    :checked
    :selected
        
        
        
    """特殊情况"""
    $(':checked')  # 它会将含checked属性的input标签 	和	含selected属性的option标签都拿到
    
    $(':selected')  # 只拿selected
    
    $('input:checked')  # 如果不想选择到含selected属性的option标签,就自己加一个限制条件
    

    5.6 筛选器方法

    $('#d1').next()  # 同级别的下一个
    
    $('#d1').nextAll()  # 同级别的下面所有
    
    $('#d1').nextUntil('.c1')  #   同级别的下面,直到.c1		(不包括最后一个)
    
                  
    $('.c1').prev()  # 同级别的上一个
    
    $('.c1').prevAll()  # 同级别的上面所有
    
    $('.c1').prevUntil('#d2')	#   同级别的上面,直到#d2		(不包括最后一个)
    
                  
    $('#d3').parent()  # 第一级父标签
    w.fn.init [p, prevObject: w.fn.init(1)]0: plength: 1prevObject: w.fn.init [span#d3]__proto__: Object(0)
                                                                               
    $('#d3').parent().parent()
    w.fn.init [div#d2, prevObject: w.fn.init(1)]
               
    $('#d3').parent().parent().parent()
    w.fn.init [body, prevObject: w.fn.init(1)]
               
    $('#d3').parent().parent().parent().parent()
    w.fn.init [html, prevObject: w.fn.init(1)]
               
    $('#d3').parent().parent().parent().parent().parent()
    w.fn.init [document, prevObject: w.fn.init(1)]
               
    $('#d3').parent().parent().parent().parent().parent().parent()
    w.fn.init [prevObject: w.fn.init(1)]
              
               
               
               
    $('#d3').parents()		# 所有父级标签(不包含document)
    w.fn.init(4) [p, div#d2, body, html, prevObject: w.fn.init(1)]
                  
                  
    $('#d3').parentsUntil('body')
    w.fn.init(2) [p, div#d2, prevObject: w.fn.init(1)]
                  
                  
                  
    $('#d2').children()  # 儿子
                  
    $('#d2').siblings()  # 同级别上下所有
                  
                  
                  
    $('div p')
    # 等价于
    $('div').find('p')  # find从某个区域内筛选出想要的标签 
                  
                  
    """下述两两等价"""
    $('div span:first')
    w.fn.init [span, prevObject: w.fn.init(1)]
    $('div span').first()
    w.fn.init [span, prevObject: w.fn.init(3)]0: spanlength: 1prevObject: w.fn.init(3) [span, span#d3, span, prevObject: w.fn.init(1)]__proto__: Object(0)
                    
                                                                                        
    $('div span:last')
    w.fn.init [span, prevObject: w.fn.init(1)]
    $('div span').last()
    
                                                                                        
    $('div span:not("#d3")')
    w.fn.init(2) [span, span, prevObject: w.fn.init(1)]
    $('div span').not('#d3')
    w.fn.init(2) [span, span, prevObject: w.fn.init(3)]
    

    5.7 选择器练习

    5.7.1 题目

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

    5.7.2 答案

    $('#i1')
    r.fn.init [div#i1.container]
               
    $('h2')
    r.fn.init [h2, prevObject: r.fn.init(1)]
    
    $('input')
    r.fn.init(9) [input#exampleInputEmail1.form-control, input#exampleInputPassword1.form-control, input#exampleInputFile, input, input, input, input, input#optionsRadios1, input#optionsRadios2, prevObject: r.fn.init(1)]
                  
    $('.c1')
    r.fn.init(2) [h1.c1, h1.c1, prevObject: r.fn.init(1)]
    
    $('.btn-default')
    r.fn.init [button#btnSubmit.btn.btn-default, prevObject: r.fn.init(1)]
               
    $('.c1,h2')
    r.fn.init(3) [h1.c1, h1.c1, h2, prevObject: r.fn.init(1)]
    
    $('.c1,#p3')
    r.fn.init(3) [h1.c1, h1.c1, p#p3.divider, prevObject: r.fn.init(1)]
                  
    $('.c1,.btn')
    r.fn.init(11) [h1.c1, h1.c1, a.btn.btn-primary.btn-lg, button.btn.btn-warning, button.btn.btn-danger, button.btn.btn-warning, button.btn.btn-danger, button.btn.btn-warning, button.btn.btn-danger, button#btnSubmit.btn.btn-default, a.btn.btn-success, prevObject: r.fn.init(1)]
                   
    $('form').find('input')
    r.fn.init(3) [input#exampleInputEmail1.form-control, input#exampleInputPassword1.form-control, input#exampleInputFile, prevObject: r.fn.init(1)]
                  
    $('label input')
    r.fn.init(6) [input, input, input, input, input#optionsRadios1, input#optionsRadios2, prevObject: r.fn.init(1)]
                  
    $('label+input')
    r.fn.init(3) [input#exampleInputEmail1.form-control, input#exampleInputPassword1.form-control, input#exampleInputFile, prevObject: r.fn.init(1)]
                  
    $('#p2~li')
    r.fn.init(8) [li, li, li, li, li, li, li, li, prevObject: r.fn.init(1)]
    
    $('#f1 input:first')
    r.fn.init [input#exampleInputEmail1.form-control, prevObject: r.fn.init(1)]
               
    $('#my-checkbox input:last')
    r.fn.init [input, prevObject: r.fn.init(1)]
    
    $('#my-checkbox input[checked!="checked"]')
    r.fn.init(3) [input, input, input, prevObject: r.fn.init(1)]0: input1: input2: inputlength: 3prevObject: r.fn.init [document]__proto__: Object(0)
    
    $('label:has("input")')
    r.fn.init(6) [label, label, label, label, label, label, prevObject: r.fn.init(1)]
    

    6 标签操作

    6.1 类相关操作

    # 操作类
    """
    js版本										   jQuery版本
    classList.add()									$(选择器).addClass()
    classList.remove()								$(选择器).removeClass()
    classList.contains()							$(选择器).hasClass()
    classList.toggle()								$(选择器).toggleClass()
    """
    
    

    6.2 css样式操作

    # css操作
    $(选择器).css('属性名','属性值')
    
    $('p').css('color','red')
    
    
    
    """一行代码将第一个p标签变成红色第二个p标签变成绿色"""
    <p>111</p>
    <p>222</p>
    $('p').first().css('color','red').next().css('color','green')
    
    
    
    # jQuery的链式操作 使用jQuery可以做到一行代码操作很多标签
    # jQuery对象调用jQuery方法之后返回的还是当前jQuery对象 也就可以继续调用其他方法
    

    6.3 位置相关操作

    # 位置操作
    $(选择器).offset()  	# 相对于浏览器窗口的位置偏移
    $(选择器).position()   # 相对于父标签的位置偏移
    
    
    scrollTop()		# 需要了解
    $(window).scrollTop()
    0
    
    $(window).scrollTop()
    969
    
    $(window).scrollTop()  # 括号内不加参数就是获取
    1733
        
    $(window).scrollTop(0)  # 加了参数就是设置
    n.fn.init [Window]
    
    $(window).scrollTop(500)
    n.fn.init [Window]
    
    $(window).scrollLeft()
    

    6.4 尺寸相关操作

    # 尺寸
    $('p').height()  # 文本高度
    20
    
    $('p').width()
    1670
    
    $('p').innerHeight()  # 文本高度+上下padding
    26
    
    $('p').innerWidth()
    1674
    
    $('p').outerHeight()  # 文本高度+上下padding+上下border
    26
    
    $('p').outerWidth()
    1674
    

    6.5 文本相关操作

    # 文本操作
    """
    操作标签内部文本
    js										jQuery
    innerText								$(选择器).text()  括号内不加参数就是获取加了就是设置
    innerHTML								$(选择器).html()
    
    
    
    $('div').text()
    "
        
            有些话听听就过去了,不要在意,都是成年人!
        
    "
    $('div').html()
    "
        <p>
            有些话听听就过去了,不要在意,都是成年人!
        </p>
    "
    
    $('div').text('你们都是我的大宝贝')	# 将div标签内部所有文本替换
    
    $('div').html('你个臭妹妹')		# 将div标签内部所有内容与标签替换成文本
    
    $('div').text('<h1>你们都是我的大宝贝</h1>')		# 不可以识别HTML语法
    
    $('div').html('<h1>你个臭妹妹</h1>')		# 可以识别HTML语法
    
    

    6.6 值获取相关操作

    js												jQuery
    .value											.val()
    """
    $('#d1').val()
    
    $('#d1').val('520快乐')  # 括号内不加参数就是获取加了就是设置
    
    
    注意:jQuery不提供文件的获取,需要转换成标签对象获取
    
    $('#d2').val()
    "C:fakepath1_测试路由.png"
    
    $('#d2')[0].files[0] 	 # 牢记两个对象之间的转换
    

    6.7 属性相关操作

    js中															jQuery
    setAttribute()											attr(name,value)
    getAttribute()											attr(name)
    removeAttribute()										removeAttr(name)
    
    
    """
    对于一般属性用attr查看,设置
    对于checked和selected要用prop查看,设置
    
    
    
    attr全称attribute(属性) 
    prop全称property(属性)
    """
    
    在用变量存储对象的时候 js中推荐使用	
    	XXXEle			标签对象
    jQuery中推荐使用
    	$XXXEle			jQuery对象
    
    
        
    let $pEle = $('p')
    
    $pEle.attr('id')
    "d1"
    
    $pEle.attr('class')
    undefined
    
    $pEle.attr('class','c1')
    
    $pEle.attr('id','id666')
    
    $pEle.attr('password','jason123')
    
    $pEle.removeAttr('password')
          
          
    
    $('#d3').attr('checked')
    "checked"
    
    $('#d2').attr('checked')
    undefined
    
    $('#d2').attr('checked')
    undefined
    
    $('#d4').attr('checked')
    undefined
    
    $('#d3').attr('checked')
    "checked"
    
    $('#d3').attr('checked','checked')  # 无效
    w.fn.init [input#d3]
    -----------------------------------------------------------------------------
               
    $('#d2').prop('checked')		// 获取id为d2的标签是否被选中(checked)
    false
               
    $('#d2').prop('checked')
    true
               
    $('#d3').prop('checked',true)		// 设置id为d3的标签为选中状态(checked=checked)
    w.fn.init [input#d3]
               
    $('#d3').prop('checked',false)
    w.fn.init [input#d3]
     
               
    """
    对于标签上有的能够看到的属性和自定义属性用attr
    对于返回布尔值比如checkbox radio option是否被选中用prop
    """
    

    6.8 标签相关操作

    """
    js													jQuery
    createElement('p')									$('<p>')
    appendChild()										append()		appendTo
    													prepend()		prependTo
    													
    insert()											$(选择器).after
    													$(选择器).before
    													remove()
    													empty()
    """
    
    
    let $pEle = $('<p>')
    $pEle.text('你好啊 草莓要不要来几个?')
    $pEle.attr('id','d1')    
    
    $('#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()  # 清空标签内部所有的内容
    
    

    7 事件

    7.1 事件的绑定方法

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

    7.2 事件绑定实例

    7.2.1 克隆

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

    7.2.2 自定义模态框

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

    7.2.3 左侧菜单

    <script>
        $('.title').click(function () {
            // 先给所有的items加hide
            $('.items').addClass('hide')
            // 然后将被点击标签内部的hide移除
            $(this).children().removeClass('hide')
        })
    </script>
    <!--尝试用一行代码搞定上面的操作-->
    

    7.2.4 返回顶部

    <script>
        $(window).scroll(function () {
            if($(window).scrollTop() > 300){
                $('#d1').removeClass('hide')
            }else{
                $('#d1').addClass('hide')
            }
        })
    </script>
    

    7.2.5 自定义登陆校验

    # 在获取用户的用户名和密码的时候 用户如果没有填写 应该给用户展示提示信息
    <p>username:
        <input type="text" id="username">
        <span style="color: red"></span>
    </p>
    <p>password:
        <input type="text" id="password">
        <span style="color: red"></span>
    </p>
    <button id="d1">提交</button>
    
    <script>
        let $userName = $('#username')
        let $passWord = $('#password')
        $('#d1').click(function () {
            // 获取用户输入的用户名和密码 做校验
            let userName = $userName.val()
            let passWord = $passWord.val()
            if (!userName){
                $userName.next().text("用户名不能为空")
            }
            if (!passWord){
                $passWord.next().text('密码不能为空')
            }
        })
        $('input').focus(function () {
            $(this).next().text('')
        })
    </script>
    

    7.2.6 input实时监控

    <input type="text" id="d1">
    
    <script>
        $('#d1').on('input',function () {
            console.log(this.value)  
        })
    </script>
    

    7.2.7 hover

    <script>
        // $("#d1").hover(function () {  // 鼠标悬浮 + 鼠标移开
        //     alert(123)
        // })
    
        $('#d1').hover(
            function () {
                alert('我来了')  // 悬浮
        },
            function () {
                alert('我溜了')  // 移开
            }
        )
    </script>
    

    7.2.8 键盘按键按下

    <script>
        $(window).keydown(function (event) {
            console.log(event.keyCode)
            if (event.keyCode === 16){
                alert('你按了shift键')
            }
        })
    </script>
    

    7.3 阻止事件

    7.3.1 阻止后续事件执行

    在该事件执行完后不再执行后面该执行的事件

    <script>
        $('#d2').click(function (e) {
            $('#d1').text('宝贝 你能看到我吗?')
            // 阻止标签后续事件的执行 方式1
            return false
            // 阻止标签后续事件的执行 方式2(该方法只能阻止标签自带的默认事件的执行)
            e.preventDefault()
        })
    </script>
    

    7.3.2 阻止事件冒泡

    事件冒泡:子标签会自动触发父标签的事件,因为子标签是被父标签包含的

    <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.4 事件委托

    在指定的范围内 将事件委托给某个标签 无论该标签是事先写好的还是后面动态创建的

    <button>是兄弟,就来砍我!!!</button>
    
    <script>
        // 给页面上所有的button标签绑定点击事件
        // $('button').click(function () {  // 无法影响到动态创建的标签
        //     alert(123)
        // })
    
        // 事件委托     
        $('body').on('click','button',function () {
            alert(123)  
            // 将body内的所有点击事件委托给button,
            // 相当于 点击body内的所有区域 都会触发button的click事件
            // 在指定的范围内 将事件委托给某个标签 无论该标签是事先写好的还是后面动态创建的
        })
    </script>
    

    8 页面加载

    js中可以使用bom操作中的window.onload使部分代码在页面加载完毕后才执行

    jquery中也有相同的方法

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

    9 动画效果

    jQuery提供了一些简单的动画效果

    传入的参数是动画的时间,毫秒为单位

    $('#d1').hide(5000)
    
    $('#d1').show(5000)
    
    $('#d1').slideUp(5000)
    
    $('#d1').slideDown(5000)
    
    $('#d1').fadeOut(5000)
    
    $('#d1').fadeIn(5000)
    
    $('#d1').fadeTo(5000,0.4)
    
    

    10 补充

    10.1 jQuery中的for循环

    # each()
    # 第一种方式
    $('div').each(function(index){console.log(index)})
    
    
    # 第二种方式
    $.each([111,222,333],function(index,obj){console.log(index,obj)})
    
    
    jQuery中使用each就无需写for循环了 
    用这两个方法更加的方便
    
    
    
    

    10.2 通过标签存储隐藏的数据

    data()能够让标签帮我们存储数据 并且用户肉眼看不见
    如:$('div').first().data('xxx','ooo')
    
    
    $('div').data('info','回来吧,我原谅你了!')
    // 为所有div标签添加键值对数据
    
                   
    $('div').first().data('info')
    "回来吧,我原谅你了!"
    // 通过键获取值
    
    $('div').last().data('info')
    "回来吧,我原谅你了!"
                 
    
    $('div').first().removeData('info')
    // 删除键对应的数据
    // 删除第一个div中的info数据
    
    
    $('div').first().data('info')
    undefined
    // 第一个div中的info数据已被删除
    
    $('div').last().data('info')
    "回来吧,我原谅你了!"
    // 最后一个div中的info未删除
    
  • 相关阅读:
    js中的原生Ajax和JQuery中的Ajax
    this的用法
    static的特性
    时政20180807
    java compiler没有1.8怎么办
    Description Resource Path Location Type Java compiler level does not match the version of the installed Java project facet Unknown Faceted Project Problem (Java Version Mismatch)
    分词器
    [数算]有一个工程甲、乙、丙单独做,分别要48天、72天、96天完成
    一点感想
    解析Excel文件 Apache POI框架使用
  • 原文地址:https://www.cnblogs.com/achai222/p/12921275.html
Copyright © 2011-2022 走看看