jQuery入门、选择器、事件、静态方法、动画

目录

第一章-jQuery基础知识

1.jQuery入门

1.1.jQuery介绍

1.2.jQuery安装

1.3.jQuery函数

1.4.jQuery对象

 2.jQuery选择器

3.jQuery事件

3.1.事件的基本使用

3.2.事件代理

3.3.事件类型

4.jQueryDOM操作

5.jQuery静态方法

5.1.数组及对象操作

5.2.测试操作

5.3.字符串操作

6.jQuery动画


第一章-jQuery基础知识

第一天的授课重点在于梳理与对比,可根据课时和学生情况选择不同的教学方式:边讲解边敲代码、对着已有代码进行梳理讲解。可结合中文文档+梳理的示例代码进行讲解。

 

在线使用:jquery (v3.6.0) - jQuery 是一个高效、精简并且功能丰富的 JavaScript 工具库。它提供的 API 易于使用且兼容众多浏览器,这让诸如 HTML 文档遍历和操作、事件处理、动画和 Ajax 操作更加简单。 | BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务

官网下载:jQuery

中文文档:jQuery API 中文文档 | jQuery 中文网jQuery API 中文文档 | jQuery API 中文在线手册 | jquery api 下载 | jquery api chm

1.jQuery入门

1.1.jQuery介绍

jQuery是一个Javascript库,是对于ECMAScript、dom、bom的一个浅封装(轻量库),让用户更方便操作。 jQuery功能: 使用CSS选择器进行元素查询 事件机制 Dom操作 属性操作 工具方法 Ajax 我们将会从以上几个点展开讲述

学习jQuery之前需具备的基础知识:

  • HTML

  • CSS

  • JavaScript

jQuery库包含**以下功能:**

  • HTML选取

  • HTML元素操作

  • CSS操作

  • HTML事件函数

  • JavaScript特效和函数

  • HTML DOM遍历和修改

  • AJAX

提示:除此之外,Jquery还提供了大量的插件,目前jQuery兼容于所有主流浏览器

1.2.jQuery安装

jQuery安装十分简单,只需要将jQuery的库导入到html中即可,我们可以下载下来也可以使用CDN资源。 一般我们在下载或者使用cdn资源的时候,都会让我们选择jquery.js 与 jquery.min.js版本,它们的区别在于jquery.min.js是经过压缩的,体积更小,适用于部署环境。而jquery适用于源码研究,我们对于jquery的学习,应该要上升到源码层次。

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

  • 网页中添加jQuery

    • jquery.com下载jQuery库

    • 从CDN中载入jQuery

  • 下载jQuery

有两个版本的jQuery可供下载:

  • Production version -用于实际的网站中,已被精简和压缩

  • Development version -用于测试和开发(未压缩,是可读的代码)

以上两个版本都可以在jQuery官网下载

jQuery库是一个JavaScript文件,可以使用HTML的<script>标签引用,但需要注意引入的jQuery的版本要和API手册版本/开发使用一致

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>01-HelloWorld.html</title>
  <!-- 本地引入 -->
  <script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
  <!-- 通过cdn引入  在线引入  通常采用 -->
  <!-- 
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   -->
  <script>
    // 1.原生JS的固定写法
    window.onload = function () {
      alert('helloworld -- js')
    }
    // 2.jQuery的固定写法
    $(document).ready(function () {
      alert('helloworld -- jquery')
    })
  </script>
</head>
<body>
</body>
</html>

jQuery API 中文文档 | jQuery API 中文在线手册 | jquery api 下载 | jquery api chm

 

1.3.jQuery函数

通过"jQuery"和"$"来调用jQuery函数

$(选择器)

通过选择器选择到符合条件的Element元素,将其保存到jQuery对象

$(html片段)

将html片段转换成Element元素,然后再封装成一个jQuery对象

$(Element元素)

将Element元素转换成一个jQuery对象

$(匿名函数)

匿名函数在文档加载完毕以后执行

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>02-jQuery的核心函数和核心对象.html</title>
  <!-- 
    1.jQuery核心函数
    简称:jQuery函数($/jQuery)
    引入jQuery库以后,直接使用$/jQuery即可
    当函数用:$(params)
    当对象用的时候:$.each()
    2.jQuery核心对象
    简称:jQuery对象 $()
    得到jQuery对象:执行jQuery函数返回的就是jQuery对象
    使用jQuery对象:$obj.xxx()
   -->
   <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   <script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
  <script>
    $(function () {
      // jQuery核心函数
      console.log($, typeof $);
      // jQuery核心对象
      console.log($(), $() instanceof Object);
    })
  </script>
</head>
<body>
  
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>03-比较原生js和jQuery.html</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    div{
      width: 100px;
      height: 100px;
      border: 1px solid black;
    }
  </style>
  <!-- 需求 通过原生js和jQuery来获取到三个div 并且修改他们的背景颜色 -->
  <!-- 导入cdn -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
  <script>
    // JS原生DOM
    window.onload = function () {
      // 1.利用原生JS来查找DOM元素
      var div1 = document.getElementsByTagName('div')[0]
      var div2 = document.getElementsByClassName('box1')[0]
      var div3 = document.getElementById('box2')
      // console.log(div1);
      // console.log(div2);
      // console.log(div3);
      // 2.利用原生JS修改背景颜色
      // div1.style.backgroundColor = 'red'
      // div2.style.backgroundColor = 'yellow'
      // div3.style.backgroundColor = 'blue'
    }
    // jQuery
    $(document).ready(function () {
      // 1.通过jQuery来查找元素
      var $div1 = $('div:first')
      var $div2 = $('.box1')
      var $div3 = $('#box2')
      // console.log($div1);
      // console.log($div2);
      // console.log($div3);
      // 2.利用jQuery来修改背景颜色
      $div1.css({backgroundColor: 'red'})
      $div2.css({
        backgroundColor: 'yellow',
        width: '200px',
        height: '200px'
      })
      $div3.css({backgroundColor: 'blue'})
    })
  </script>
</head>
<body>
  <div></div>
  <div class="box1"></div>
  <div id="box2"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04-jQuery和js入口函数的区别.html</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
  <script>
    /*
      前提:图片或者是资源是通过网络数据获取的
      需求:获取网络图片的宽度或高度
      区别一 原生JS和jQuery入口函数的加载模式不同
      原生JS会等到DOM元素加载完毕,并且图片也加载完毕才会执行
      jQuery会等到DOM元素加载完毕,但不会等到图片也加载完毕
    */
      // 原生JS入口函数
      window.onload = function () {
        // 获取img
        var img = document.getElementsByTagName('img')[0]
        //var img=document.images[0];
        // 通过原生JS拿到DOM元素的宽高
        var width = window.getComputedStyle(img).width
        console.log('JS' ,width)
      }
      // jQuery入口函数
      $(document).ready(function () {
        // 获取img
        var $img = $('img')
        // console.log($img);
        // 通过jQuery来获取img的宽度
        var $width = $img.width()
        console.log('jquery', $width);//因网速、浏览器缓存,结果可能是null或者0或者470
      })
    /*
      区别2 
      原生的JS如果编写了多个入口函数,后面编写的会覆盖前面编写的
      jQuery如果编写了多个入口函数,后面的不会覆盖前面的
    */
      // 原生JS入口函数
      // 后面覆盖前面
      window.onload = function () {
        alert('第一个入口函数js')
      }
      window.onload = function () {
        alert('第二个入口函数js')
      }
      // jQuery入口函数
      // 依次执行
      $(document).ready(function () {
        alert('第一个入口函数jquery')
      })
      $(document).ready(function () {
        alert('第二个入口函数jquery')
      })
      
    /*
      jQuery入口函数的写法:
    */
      // 第一种写法
      $(document).ready(function () {
        alert('hello jQuery')
      })
      // 第二种写法
      jQuery(document).ready(function () {
        alert('hello jQuery')
      })
      // 第三种写法 (推荐写法)
      $(function () {
        alert('hello jQuery')
      })
      // 第四种写法
      jQuery(function () {
        alert('hello jQuery')
      })
  </script>
</head>
<body>
  <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594098348314&di=40aafcc3476781ff40766f2e9b5c165a&imgtype=0&src=http%3A%2F%2Fa1.att.hudong.com%2F62%2F02%2F01300542526392139955025309984.jpg" alt="">
</body>
</html>

1.4.jQuery对象

jQuery对象是类数组对象,jQuery的方法都是对类数组中的元素的批量操作 注意:jQuery对象可以调用jQuery.prototype中声明的方法,普通的Element元素则不能调用。在使用jquery的时候,拿到一个对象务必要搞明白该对象是Element元素还是jQuery实例 如下代码,this是Element元素,如果想调用jQuery方法,需要使用$()将其转换为jQuery实例

$("form").on("submit",function(){
  this
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>05-jQuery和JS的基本使用小案例.html</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
  <script>
    // 原生JS
    window.onload = function () {
      var btn1 = document.getElementById('btn1')// 获取id为btn1的元素
      btn1.onclick = function () {// btn1设置点击事件
        console.log("btn1",this);
        // 获取到input输入框中的值
        var username = document.getElementById('username').value
        alert(username)
      }
    }
    // jQuery
    /*
      jQuery核心函数:($/jQuery)
      jQuery核心对象:执行$()返回的对象
    */
    $(function () {
      $('#btn2').click(function () {// 获取id为btn2的按钮,设置点击事件
        console.log("btn2",this,$(this),$('#btn2'));
        // 获取到input输入框中的值
        var username = $('#username').val()
        alert(username)
      })
    })
  </script>
</head>
<body>
  <!-- 需求:点击按钮,提示输入框中输入的值 -->
  用户名:<input type="text" id="username"><br>
  <button id="btn1">确定(原生)</button>
  <button id="btn2">确定(jQuery)</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>06-jQuery核心函数与对象的使用.html</title>
</head>
<body>
  <div>
    <button id="btn">测试</button><br>
    <input type="text" name="msg1"><br>
    <input type="text" name="msg2"><br>
  </div>
  <!-- 
    1.jQuery核心函数作为一般函数调用的时候:$(param)
      1-参数为函数: 当DOM加载完成后,执行此回调函数
      2-参数为选择器字符串:查找所有匹配的标签,并将它们封装成jQuery对象
      3-参数为DOM对象:将DOM对象封装成jQuery对象
      4-参数为HTML标签字符串(很少用):创建标签对象并封装成jQuery对象
    2.jQuery静态方法,$作为对象使用:$.xxx()
      1-$.each() 隐式遍历数组
      2-$.trim 取出两端的空格 
      等等
   -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    // 需求一:点击按钮,显示按钮的文本标题,增加一个新的输入框
    // 1.jQuery入口函数
    // 1-参数为函数: 当DOM加载完成后,执行此回调函数
    $(function () { //绑定文档加载完成的监听
      // 2.获取id为btn的按钮
      // 2-参数为选择器字符串:查找所有匹配的标签,并将它们封装成jQuery对象
      $('#btn').click(function () {
        // this是什么? 发生事件的dom元素对象 当前就是btn按钮
        // 3.获取button按钮中的标题
        // alert(this.innerHTML)
        // jQuery获取元素内容
        // 3-参数为DOM对象:将DOM对象封装成jQuery对象
        alert($(this).html())
        // 增加新的输入框
        // 4-参数为HTML标签字符串:创建标签对象并封装成jQuery对象
        $('<input type="text" name="msg3"><br>').appendTo('div')
      })
      // 需求二 遍历输出数组中的所有元素值
      var arr = [1,2,3,4,5,6]
      // 1-$.each() 隐式遍历数组
      $.each(arr, function (index, item) {
        console.log(index, item);
      })
      // 需求三 去掉 my jQuery 两端的空格
      var str = '     my jQuery    '
      console.log('----'+str.trim()+'-------');
      console.log('----' + $.trim(str) + '-------');
    })
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>07-jQuery对象.html</title>
</head>
<body>
  <button>测试一</button>
  <button class="b">测试二</button>
  <button id="btn3">测试三</button>
  <button class="b">测试四</button>
  <!-- 
    1.jQuery对象是一个包含所有匹配的任意多个dom元素的伪数组对象
    2.基本行为
      * size()/length : 包含的DOM元素的个数
      * [index]/get(index) : 得到对应位置的DOM元素
      * each() : 遍历包含的所有DOM元素
      * index() : 得到所在元素的下标
   -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(function () {
      // 获取所有的button
      var $btns = $('button')
      // console.log($btns);
      // 需求一 统计一共有多少个按钮
      // size()/length : 包含的DOM元素的个数
      console.log('button个数为' + $btns.size());
      console.log('button个数为' + $btns.length);
      // 需求二 取出第二个button的文本
      // [index] / get(index) : 得到对应位置的DOM元素
      console.log($btns[1].innerHTML);
      console.log($btns.get(1).innerHTML);
      // 需求三 输出所有button标签的文本
      // each() : 遍历包含的所有DOM元素
      // $.each($btns, function (index, item) {
      //   console.log(index, item.innerHTML);
      // })
      $btns.each(function (index, item) {
        console.log(index, item.innerHTML, this);
      })
      // 需求四 输出测试三按钮是所有按钮的第几个
      // index() : 得到所在元素的下标
      console.log($('#btn3').index());
      console.log($('.b').index());
    })
  </script>
</body>
</html>

 2.jQuery选择器

jQuery的选择器与CSS3中的选择器几乎完全一致,这里就不再赘述。总体梳理:

  1. 基本选择器

  2. 层次选择器

  3. 伪类选择器

  4. 伪元素选择器器

  5. 属性选择器 具体用法如下:

    $("form")
    $("ul.nav > li")

    jQuery中所有选择器都以美元符号开头:$()

    例如:

    元素选择器

    在页面中选取所有<div>元素

    $("div")

    实例

  6. 用户点击按钮后所有<div>元素都隐藏

    $(document).ready(function(){ 
      $("button").click(function(){ 
        $("div").hide();
       });
    });

    #id选择器

  7. 通过 id 选取元素语法如下

    $("#div1")

    .class选择器

  8. jQuery 类选择器可以通过指定的 class 查找元素

    $(".box")

    实例

  9. 用户点击按钮后所有带有 class="box" 属性的元素都隐藏

    $(document).ready(function(){ 
      $("button").click(function(){ 
        $(".box").hide(); 
        }); 
    });

    更多实例:

     

    更多梳理的代码:  

     

3.jQuery事件

jQuery的事件绑定与Element元素不同,不可以使用onxxx属性,也不能使用addEventListener,而是使用on(),可以理解为on是对于Element元素事件绑定的封装。 on()也支持事件代理。

  1. on(event,[selector],[data],fn)

  2. off(event,[selector],fn)

  3. one(event,[selector],fn)

  4. trigger(event,[data]) jQuery的事件绑定还支持快捷绑定

  5. click([data],fn)

 

3.1.事件的基本使用

jQuery事件方法语法

  • on() off()

  • bind() unbind()

  • 快捷绑定click()等

在jQuery中,大多数DOM事件都有一个等效都jQuery方法

页面中指定一个点击事件:

$("p").click();

下一步是定义触发事件的内容:

$("p").click(function(){
  //动作触发后执行的代码!!
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>01-事件的基本使用.html</title>
</head>
<body>
  <button>新增</button>
  <button>修改</button>
  <div>标题</div>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
  <script>
    $(function () {
      // 第一个参数 事件类型 第二个参数(可选的) 要传递的参数 第三个参数 事件处理函数
       /*
       $('button').bind('click', '123', function (event) {
         console.log('button点击');
         console.log(event);
         console.log(event.data);//123
       })
       */
      // 点击新增或者修改按钮,改变div内部的内容
      $('button').bind('click', function (event) {
        // 通过event.target(DOM节点,可以拿到内部的内容) 来判断当前是哪个按钮点击
        // console.log(event.target);
        // console.log(event.target.innerHTML);
        if($(event.target).html() === '新增'){
          $('div').html('新增学生信息')
        }else{
          $('div').html('修改学生信息')
        }
      })
      // 解绑 unbind() 无参时 解除绑定的所有事件
      // $('button').unbind()
      // 解绑 unbind('click') 传递参数->事件类型
      // $('button').unbind('click')
      // 解绑 unbind() 解绑click对应的事件
      function clickEvent() {
        console.log('我是click事件');
      }
      $('button').click(clickEvent)
      // 第一个参数 事件类型 第二个参数 事件名称
      $('button').unbind('click', clickEvent)
    })
  </script>
</body>
</html>

3.2.事件代理

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>02-事件代理.html</title>
</head>
<body>
  <button>点我啊</button>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
  <script>
    // 点击body
    // 第一个参数 事件类型 第二个参数(可选) 将要代理谁 第三个参数(可选) 传递给事件内部的参数 第四个参数 事件处理程序
    // $('body').on('click', function (event) {
    //   console.log(event);
    // })
    // button做代理   所有button上触发的事件都会冒泡到body上触发下面的点击事件
    $('body').on('click','button', [1,2], function (event, a, b) {
      console.log(event, a, b);
    })
    // 事件解绑 移除代理 使用off
    // $('body').off('click', 'button')
    
    //不用看
    // 模拟事件执行 trigger 第一个参数 事件类型 第二个参数 数组参数(传递给形参)
    $('button').trigger('click', [1, 2])
  </script>
</body>
</html>

3.3.事件类型

常用**的jQuery事件快速绑定方法**

1.$(document).ready()

$(document).ready()方法允许我们在文档完全加载完后执行函数

2.click()

click()方法是当按钮点击事件被触发时会调用一个函数

3.dbclick()

当双击元素时,会发生dbclick事件

4.mouseenter()

当鼠标指针穿过元素时,会发生mouseenter事件

5.mouseleave()

当鼠标指针离开元素时,会发生mouseleave事件

6.mousedown()

当鼠标指针移动到元素上方,并按下鼠标按键时,会发生mousedown事件

7.mouseup()

当元素上松开鼠标按钮时,会发生mouseup事件

8.hover()

hover()方法用于模拟光标悬停事件

当鼠标移动到元素上时,会触发指定当第一个函数(mouseenter);当鼠标移出这个元素时,会触发指定当第二个函数(mouseleave)

9.blur()

当元素失去焦点时,发生blur事件

10.keydown()

键盘事件:按键按下事件

11.keyup()

键盘事件:按键抬起事件

12.表单事件等等

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>03-事件类型方法.html</title>
</head>
<body>
  <p>一段文字</p>
  <button>点我啊</button><br>
  输入一些东西: <input type="text">
  <form action="">
    name:
    <input type="text" value="zhangsan">
    <span style="display: none;">请输入你的名字</span>
    <br>
    <input type="submit" value="提交">
  </form>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
  <script>
    $(function () {
      //click() 鼠标单击事件
      //当点击事件在某个<p>元素上触发时,隐藏当前当<p>元素
      $("p").click(function(){
        $(this).hide();
      });
      // dblclick()   鼠标双击事件
      $('button').dblclick(function () {
        alert('dblclick')
      })
      // mouseenter() 鼠标进入事件  不支持子元素
      $('button').mouseenter(function () {
        console.log('mouseenter:你的鼠标移到了button的元素上!');
        $('button').css('background', 'red')
      })
      // mouseleave() 鼠标离开事件  不支持子元素
      $('button').mouseleave(function () {
        console.log('mouseleave:再见,你的鼠标离开了该button');
        $('button').css('background', 'blue')
      })
      // mousedown()  当鼠标指针移动到元素上方,并按下鼠标按键时
      $('button').mousedown(function () {
        console.log('mousedown:鼠标在该按钮上按下');
      })
      // mouseup()  当元素上松开鼠标按钮时,会发生mouseup事件
      $('button').mouseup(function () {
        console.log('mouseup:鼠标在button上松开');
      })
      // hover()    鼠标悬停事件
      $('button').hover(function () {
        console.log('hover');
        $(this).css("background-color","#cccccc");
      })
      //blur() 失去焦点
      $("input").blur(function(){ 
        $(this).css("background-color","#ffffff"); 
      });
      // 键盘事件
      // keydown 按键按下事件
      $('input').keydown(function () {
        $('input').css('background', 'blue')
      })
      // keyup 按键抬起事件
      $('input').keyup(function () {
        $('input').css('background', 'yellow')
      })
      // submit()
      $('form').submit(function () {
        alert('submit')
        return false;
      })
      // focus
      $('input:text').focus(function () {
        // 动画
        $('span').css('display','inline').fadeOut(3000)
      })
    })
  </script>
</body>
</html>

4.jQueryDOM操作

jQuery中提供了一系列的操作DOM节点的api,用于解决DOM原生API无法进行批量操作并且功能性较差的弊端。 插入方法:append、appendTo、prepend、prependTo、after、before、insertBefore、insertAfter 包裹方法:wrap、unwrap、wrapAll、wrapInner、 替换方法:replaceWith、replaceAll 移除方法:empty、remove、detach 克隆方法:clone

通过 jQuery,可以很容易地添加新元素/内容。

我们将学习用于添加新内容的四个 jQuery 方法:

  • append() - 在被选元素的结尾插入内容(仍然在该元素的内部)

  • prepend() - 在被选元素的开头插入内容

  • after() - 在被选元素之后插入内容

  • before() - 在被选元素之前插入内容

  • 等等

复制节点:

原生DOM有 cloneNode(true/false) 浅复制false 深复制true。是否复制内部内容,并不涉及事件的复制。默认浅复制

jQuery对象有 clone(true/false) 浅复制false 深复制true。会复制内容,是否复制事件。默认浅复制

属性操作 在dom中,我们通过setAttribute/getAttribute/style来操作元素属性,jQuery中提供了更加便捷的方法 属性:attr、removeAttr、prop、removeProp css:addClass、removeClass、toggleClass、wrapInner、 内容:html、text、val

jQuery 拥有可操作 HTML 元素和属性的强大方法

三个简单实用的用于 DOM 操作的 jQuery 方法:

  • text() - 设置或返回所选元素的文本内容

  • html() - 设置或返回所选元素的内容(包括 HTML 标记)

  • val() - 设置或返回表单字段的值

更多梳理的代码:

 

5.jQuery静态方法

静态方法属于定义在jQuery函数上的方法,通过jQuery或者$直接调用的方法 数组及对象操作:each、map、toArray、merge 测试操作:type、isEmptyObject、isPlainObject、isNumberic 字符串操作:param、trim

因使用频率高,本章节内容重点讲解,方便以后编码使用、看源码使用

5.1.数组及对象操作

each()

通用遍历方法,可用于遍历对象和数组

不同于遍历 jQuery 对象的 $().each() 方法,此方法可用于遍历任何对象。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略

例如:

// 遍历对象
var obj = {
    name: 'zach',
    age: 18,
    height: '1.88'
}
// 第一个参数 要遍历的数组或对象 第二个参数 处理函数
$.each(obj, function (key, value) {
    console.log(key, value);
})
//遍历数组
$.each( [0,1,2], function(i, n){
    alert( "Item #" + i + ": " + n );
});

map() 将一个数组中的元素转换到另一个数组中

作为参数的转换函数会为每个数组元素调用,而且会给这个转换函数传递一个表示被转换的元素作为参数。转换函数可以返回转换后的值、null(删除数组中的项目)或一个包含值的数组,并扩展至原始数组中

例如:

var arr=$.map( [0,1,2], function(n){
  return n + 4;
});

filter()

将符合要求的元素选中返回

//<div>hello1</div>
//<div>hello2</div>
//<div>hello3</div>
//<div>hello4</div>
// 过滤出div文本后缀大于2的元素
var $result = $('div').filter(function (index, item) {
  // console.log(item);// item DOM节点
  // 获取内部文本内容
  var text = $(item).text()
  // console.log(text);
  // 截取字符串的最后一位
  text = text.slice(text.length - 1)
  return text > 2
})
console.log($result);

toArray()

把jQuery集合中所有DOM元素恢复成一个数组

例如:

console.log($('li').toArray());

merge() 合并两个数组

返回的结果会修改第一个数组的内容——第一个数组的元素后面跟着第二个数组的元素。要去除重复项,请使用$.unique()

例如:

console.log($.merge( [0,1,2], [2,3,4] ));

注意:更多其他关于数组及对象的操作,请移步jQuery API 中文文档 | jQuery API 中文在线手册 | jquery api 下载 | jquery api chm

5.2.测试操作

type()

用于检测obj的数据类型

console.log($.type($)); //function
console.log(jQuery.type(true) === "boolean");//true
console.log(jQuery.type(3) === "number");//true
console.log(jQuery.type("test") === "string");//true
console.log(jQuery.type(function(){}) === "function");//true
console.log(jQuery.type([]) === "array");//true
console.log(jQuery.type(new Date()) === "date");//true
console.log(jQuery.type(/test/) === "regexp");//true

isEmptyObject()

测试对象是否是空对象(不包含任何属性),这个方法既检测对象本身的属性,也检测从原型继承的属性(因此没有使用hasOwnProperty方法更具体)

console.log(jQuery.isEmptyObject({})); // true
console.log(jQuery.isEmptyObject({ foo: "bar" })); //false
function Animal(name){this.name=name}
var cat = new Animal("猫咪");
function BuOu(){}
BuOu.prototype=cat;
cat.constructor = BuOu;//布偶和cat建立夫妻关系,从而布偶的对象和Animal建立继承关系
var diandian = new BuOu();//原型链是:Object.prototype--Animal.prototype--BuOu.prototype/cat--diandian
console.log(jQuery.isEmptyObject(cat));//false; 因为cat包含了可枚举的属性name
console.log(jQuery.isEmptyObject(diandian));//false; 因为点点的父亲cat包含了可枚举的属性name,所以点点不是一个空对象
diandian.age=10;
console.log(diandian.hasOwnProperty('name'));//false;
console.log(diandian.hasOwnProperty('age'));//true;

isPlainObject()

测试对象是否是纯粹的对象(通过 "{}" 或者 "new Object" 创建的)

console.log(jQuery.isPlainObject({})); // true
console.log(jQuery.isPlainObject("test")); // false
console.log($.isPlainObject($('body')))//false

isNumberic()

确定它的参数是否是一个数字

$.isNumeric() 方法检查它的参数是否代表一个数值。如果是这样,它返回 true。否则,它返回false。该参数可以是任何类型的

console.log($.isNumeric("-10"));  // true
console.log($.isNumeric(16));     // true
console.log($.isNumeric(0xFF));   // true
console.log($.isNumeric("0xFF")); // true
console.log($.isNumeric("8e5"));  // true (exponential notation string)
console.log($.isNumeric(3.1415)); // true
console.log($.isNumeric(+10));    // true
console.log($.isNumeric(0144));   // true (octal integer literal)
console.log($.isNumeric(""));     // false
console.log($.isNumeric({}));     // false (empty object)
console.log($.isNumeric(NaN));    // false
console.log($.isNumeric(null));   // false
console.log($.isNumeric(true));   // false
console.log($.isNumeric(Infinity)); // false
console.log($.isNumeric(undefined)); // false
注意:其他更多关于测试的操作,例如$.isArray(obj)判断是否是数组、$.isFunction(obj)判断是否是函数等,请移步[https://jquery.cuishifeng.cn/](https://jquery.cuishifeng.cn/)

5.3.字符串操作

param()

将表单元素数组或者对象序列化。是.serialize()的核心方法

例如:

var obj={name:"张三",age:12}
var str = jQuery.param(obj);
$("#results").text(str);

parseJSON()

解析json字符串转换为js对象/数组

// 原生js:
// JSON.parse(jsonString) json字符串 转 js对象/数组
// JSON.stringify(jsonObj/jsonArr) js对象/数组 转 json字符串
// 2.$.parseJSON(json): 解析json字符串转换为js对象/数组
var json = '{"name":"Tom", "age":12}'// 模拟一个json对象
console.log($.parseJSON(json)); // 将json对象转换为js对象
json = '[{"name":"Tom", "age":12},{"name":"lilly", "age":12}]';// json数组
console.log($.parseJSON(json));// 将json对象转换为js数组

trim() 去掉字符串起始和结尾的空格,多用于用户数据的清洗

例如:

console.log('--'+$.trim(" hello, how are you? ")+'--');

注意:其他更多关于字符串的操作,请移步jQuery API 中文文档 | jQuery API 中文在线手册 | jquery api 下载 | jquery api chm

6.jQuery动画

更多梳理的代码:

 

  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值