jQuery 基础知识

34 篇文章 0 订阅
2 篇文章 0 订阅

目录

一、jQuery总体概述

1、jQuery安装

 2、jQuery函数

 js的入口函数

jQuery的入口函数

js入口函数和jQuery入口函数的区别

 3、jQuery对象

二、jQuery选择器

三、jQuery事件

1、事件类型

2、jQuery事件的基本使用

四、jQuery的DOM操作

五、jQuery静态方法

六、jQuery动画


一、jQuery总体概述

jQuery是一个Javascript库,是对于ECMAScript、dom、bom的一个浅封装,让用户更方便操作。

1、jQuery安装

jQuery安装十分简单,只需要将jQuery的库导入到html中即可,我们可以下载下来也可以使用CDN资源。

第一种:通过CDN引入:

网址:https://www.bootcdn.cn/jquery/

 第二种:本地引入

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 通过CDN引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <!-- 本地引入 -->
  <script src="./jquery.js"></script>
</head>
<body>
  
</body>
</html>

 2、jQuery函数

我们通过" jQuery "和" $ "来调用jQuery函数 (选择器) ,然后通过选择器选择到符合条件的Element元素,将其保存到jQuery对象。

jQuery核心函数:
简称:jQuery函数 ($/jQuery)
引入jQuery库以后,直接使用$/jQuery即可
当函数用:$(params)
当对象用的时候:$.each()


jQuery核心对象:
简称:jQuery对象   $()
得到jQuery对象:执行jQuery函数返回的就是jQuery对象
使用jQuery对象:$.xxx()

我们可以将jQuery函数和对象打印看一下:

<script>
    console.log('jQuery函数', $, typeof $);
    console.log('jQuery函数', jQuery, typeof jQuery);
    console.log('jQuery对象', jQuery(), typeof jQuery());
    console.log('jQuery对象', $(), typeof $());
    console.log($().__proto__ === jQuery.prototype); //$()是jQuery的实例对象
</script>

    

使用:

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

$('<p></p>').appendTo('body'); //添加一个p元素

$(Element元素) :将Element元素转换成一个jQuery对象

$('#one') //获取id名为one的元素并转换成jQuery实例对象

$(匿名函数) :匿名函数在文档加载完毕以后执行

$(function(){}) //入口函数

 js的入口函数

<script>
    window.onload = function(){
      
    }
</script>

jQuery的入口函数

jQuery入口函数有四种写法:

<script>
    //第一种
    $(document).ready(function(){
		alert('我是入口函数1')
	});
    //第二种
	jQuery(document).ready(function(){
		alert('我是入口函数2')
	});
    //第三种
	$(function(){
		alert("我是入口函数3,推荐写法")
	})
    //第四种
	jQuery(function(){
		alert("我是入口函数4")
	})
</script>

js入口函数和jQuery入口函数的区别

区别一:加载模式不同

原生JS会等到DOM元素加载完毕,并且图片也加载完毕才会执行;
jQuery会等到DOM元素加载完毕,但不会等到图片也加载完毕。

例子:获取网络图片的宽高

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 通过CDN引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    //原生js入口函数
    window.onload = function(){
      var img=document.getElementsByTagName('img')[0];
	  // js可以使用window方法getComputedStyle() 获取标签的所有属性
	  console.log(window.getComputedStyle(img).width); //'751px'
	  console.log(window.getComputedStyle(img).height); //'500px'
    }

    //jQuery入口函数
    $(function(){
      var img=$('img');
	  console.log(img.width()); //因网速、浏览器缓存,结果可能是null或者0或者751
	  console.log(img.height());//因网速、浏览器缓存,结果可能是null或者0或者500
    })
  </script>
</head>
<body>
  <img src="https://img1.baidu.com/it/u=1966616150,2146512490&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1661619600&t=e8072b5bd977855fce56f13f63ee3a71" alt="">
</body>
</html>

区别二:

原生的JS如果编写了多个入口函数,后面编写的会覆盖前面编写的
jQuery如果编写了多个入口函数,后面的不会覆盖前面的

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 通过CDN引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    // 原生js的入口函数:只会执行一个,后面的会覆盖掉前面的
	window.onload=function(){
		alert('我是入口函数1')
	}
	window.onload=function(){
		alert('我是入口函数2')
	}
    // jquery的入口函数:入口函数依次执行
    $(function(){
      alert('我是入口函数1')
    });
    $(function(){
      alert('我是入口函数2')
    });
  </script>
</head>
<body>
</body>
</html>

 3、jQuery对象

jQuery对象是类数组对象,jQuery的方法都是对类数组中的元素的批量操作。

注意:jQuery对象可以调用 jQuery.prototype 中声明的方法,普通的Element元素则不能调用。在使用jquery的时候,拿到一个对象务必要搞明白该对象是Element元素还是jQuery实例。

如下代码,this是Element元素,如果想调用jQuery方法,需要使用$()将其转换为jQuery实例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 通过CDN引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(function(){
      $('div').click(function(){
        var res = $(this).html() //此处不可以写成 this.html()
        console.log(res);
      })
    })
  </script>
</head>
<body>
  <div>我是一个div</div>
</body>
</html>

jQuery核心函数作为一般函数调用的时候:$(param)
      1、参数为函数:当DOM加载完成后,执行此回调函数
      2、参数为选择器字符串:查找所有匹配的标签,并将它们封装成jQuery对象
      3、参数为DOM对象:将DOM对象封装成jQuery对象
      4、参数为HTML标签字符串(很少用):创建标签对象并封装成jQuery对象


jQuery静态方法的使用:$.xxx()
      1、$.each() 隐式遍历数组
      2、$.trim 取出两端的空格 
      3、等等……

这些后面还会讲到,继续往下看吧! 

二、jQuery选择器

jQuery的选择器与CSS3中的选择器几乎完全一致,总体梳理:

  1. 基本选择器

  2. 层次选择器

  3. 伪类选择器

  4. 伪元素选择器器

  5. 属性选择器

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

例如:

$("div") //元素选择器
$("ul.nav > li") //子代选择器
$('input[type="text"]') //属性选择器
$('#one,.two') //并集选择器

三、jQuery事件

1、事件类型

  1. click()  当按钮点击事件被触发时会调用一个函数
  2. dbclick()  当双击元素时,会发生dbclick事件
  3. mouseenter()  当鼠标指针穿过元素时,会发生mouseenter事件
  4. mouseleave()  当鼠标指针离开元素时,会发生mouseleave事件
  5. mousedown()  当鼠标指针移动到元素上方,并按下鼠标按键时,会发生mousedown事件
  6. mouseup()  当元素上松开鼠标按钮时,会发生mouseup事件
  7. hover()  用于模拟光标悬停事件。当鼠标移动到元素上时,会触发(mouseenter);当鼠标移出这个元素时,会触发(mouseleave)
  8. blur()  当元素失去焦点时,发生blur事件
  9. keydown()  键盘事件:按键按下事件
  10. keyup()  键盘事件:按键抬起事件

2、jQuery事件的基本使用

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

绑定事件       on(event,[selector],[data],fn)        (也可做事件代理)

                     bind(event,[selector],[data],fn)

解绑事件       off(event,[selector],fn)

                     unbind(event)

                     one(event,[selector],fn)  (只执行一次)

模拟事件        trigger(event,[data])

快捷绑定        click([data],fn)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 通过CDN引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
		$(function(){
			var btn=$('button:first');

			// 绑定事件 on(事件类型,传参(可选),事件处理程序)
			btn.on('click',[1,2,3],function(event){
				console.log(event,'事件对象');
				console.log(event.data); //获取参数
				$(event.target).html('不想被点'); //改变元素内容
			});

			// 模拟点击事件(不需要我们点击就自动执行)
			btn.trigger('click');

			// 解绑事件
			btn.off('click');

      //-----------------------------------------------------------------

			// 绑定事件方法 bind绑定 参数(事件类型,参数(可选),事件处理程序)
			btn.bind('click',[1,2,3],function(e){
				console.log(e,'事件对象');
			});

            // 解绑事件
			btn.unbind(); //无参 代表解除绑定的所有事件
            btn.unbind('click'); //有参 代表解绑相应的事件

      //--------------------------------------------------------------------

			// one 绑定事件:只能点击一次
			btn.one('click',function(e){
				console.log('我被绑定了',e);
			});

      //--------------------------------------------------------------------
      
			// 事件代理 on(事件类型,代理对象,事件处理程序)
            $('body').on('click','button',function(){
                $('button').html('我被点击了')
            })

      //---------------------------------------------------------------------

			// 其他事件类型的使用
			$('button').dblclick(function(){
				console.log('我被双击了');
			});
			$('button').mouseenter(function(){
				$(this).css({
					backgroundColor:'red'
				})
			});
			$('button').mouseleave(function(){
				$(this).css({
					backgroundColor:'blue'
				})
			})
			$('input[type="text"]').focus(function(){
				$(this).css({
					backgroundColor:'red'
				})
			})
			$('input[type="text"]').blur(function(){
				$(this).css({
					backgroundColor:'blue'
				})
			})
		})
  </script>
</head>
<body>
  <input type="text">
	<button>点击我</button>
	<button>点击我</button>
	<button>点击我</button>
	<button>点击我</button>
	<button>点击我</button>
	<button>点击我</button>
</body>
</html>

四、jQuery的DOM操作

jQuery中提供了一系列的操作DOM节点的api,用于解决DOM原生API无法进行批量操作并且功能性较差的弊端。

插入方法:append、appendTo、prepend、prependTo、after、before、insertBefore、insertAfter

包裹方法:wrap、unwrap、wrapAll、wrapInner、

替换方法:replaceWith、replaceAll

移除方法:empty、remove、detach

克隆方法:clone

用于添加新内容的四个 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

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

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

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

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 通过CDN引入 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
		$(function(){
			// append插入内容到元素尾部
			$('div:first').append('<p>我是一个p标签</p>');
			// 创建一个div添加到body尾部
			$('<div>我是块级元素</div>').appendTo('body');


			// 克隆节点 针对事件 浅克隆不克隆事件 深克隆克隆事件
			$('button:first').click(function(){
				console.log('我被点击了');
			})
			// clone方法无参:浅克隆; 有参true:深克隆
			$('button:first').clone(true).appendTo('body');


			// 获取div的id属性值
			// attr:1个参数 获取该属性名对应的属性值
			//      2个参数 给当前dom元素设置/修改属性
			console.log($('div:first').attr('id','newId'));


			// removeAttr 删除属性
			$('div:first').removeAttr('title');

      
			// 添加类名
			$('div:first').addClass('active');
			// 删除类名 删除对应的样式
			$('div:first').removeClass('two');
			// 切换类名 --对应的是删除或者是添加类名 
			$('div:first').click(function(){
				$(this).toggleClass('active')
			});


			// 获取body标签内部的内容
			console.log($('body').html());//innerHTML 识别代码片段
			console.log($('body').text());//innerText
		})
	</script>
</head>
<body>
	<button>确定</button>
	<div id="one" class="two" title="我是一个div">我是一个div</div>
</body>
</html>

五、jQuery静态方法

静态方法属于定义在jQuery函数上的方法,通过jQuery或者$直接调用的方法

数组及对象操作:each、map、merge

测试操作:type、isEmptyObject、isPlainObject、isNumberic

字符串操作:param、trim

each()

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

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

map()

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

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

merge()

合并两个数组

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

param()

将表单元素数组或者对象序列化。

parseJSON()

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

trim()

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

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script>
		$(function(){
			var obj={
				name:'zhangsan',
				age:12
			}
      //遍历对象
			$.each(obj,function(key,value){
				console.log(key,value);
			});

			var arr=[1,2,3];
      //遍历数组
			$.each(arr,function(index,item){
				console.log(index,item);
			});

	  // map 映射 参数:要操作的数组 回调函数
			var res=$.map(arr,function(item,index){
				return item + 4
			});
			console.log(res);

	  // 合并数组 merge 
			console.log($.merge([1,2,3],[4,5,6]));

	  // 将对象转换成查询字符串
			var obj={
				page:1,
				pageSize:10
			}
			console.log($.param(obj));
			var obj1='{"name":"zhangsan","age":12}';
			console.log($.parseJSON(obj1));

      //去掉字符串起始和结尾的空格
          var str = '   hello world!   '
          console.log($.trim(str));
		})
	</script>
</head>
<body>
	<div>我是一个div</div>
	<div>我是一个div</div>
	<div>我是一个div</div>
</body>
</html>

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

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

六、jQuery动画

hide() 隐藏

show() 显示

toggle() 切换,如果是隐藏的就显示出来,如果是显示的就隐藏起来

fadeOut() 淡出,可以添加参数,表示淡出的时间(单位:毫秒)

fadeIn() 淡入,可以添加参数,表示淡入的时间(单位:毫秒)

fadeToggle() 淡入淡出进行切换

slideUp() 向上收起

slideDown() 向下展开

slideToggle() 收起和展开进行切换

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <style>
    div{
      width: 100px;
      height: 100px;
      background-color: pink;
      margin-top: 10px;
    }
  </style>
</head>
<body>
  <button>切换</button>
  <div></div>
  <script>
    $('button:first').click(function(){
        // $('div').hide();
        // $('div').show();
        // $('div').toggle()

        // $('div').fadeOut(1000)
        // $('div').fadeIn(1000)
        // $('div').fadeToggle()

        // $('div').slideUp()
        // $('div').slideDown()
        // $('div').slideToggle()
    })
  </script>
</body>
</html>

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值