什么是jQuery?

jQuery 是一个高效、精简并且功能丰富的 JavaScript 工具库。它提供的 API 易于使用且兼容众多浏览器,这让诸如 HTML 文档遍历和操作、事件处理、动画和 Ajax 操作更加简单。它并不能代替JavaScript

  1. jquery 是一个javascript库. 对javascript进行封装可以更加优雅的写js代码
  2. jquery主要是通过操作html中dom 的方式进行代码编写.和设计
  3. jquery的优点是简单.易用. 能简写很多的javascript代码
  4. 使用jquery可以很快速的构建前端页面.一些javascript特效.
  5. jquery是javascript的一个库同时也是对js更加简便操作

jQuery官网地址:https://jquery.com/
jQuery API 中文文档:https://www.jquery123.com/

如何引入jQuery库

  1. 官网下载通过script引入
    注意:我们这里学习中下载未压缩版本即可,实际项目上线中才引入压缩过后的min.js版本
    <script src="./jquery-3.6.0.js"></script>

  1. 通过百度的CDN引入在线链接
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

初体验原生JS和jQuery对比

  1. <input type="button" value="显示效果" id="btn">
  2. <div></div>
  3. <script>
  4. // 原生JavaScript
  5. document.querySelector('#btn').addEventListener("click", function() {
  6. let divObj = document.querySelector('div');
  7. divObj.style.width = "200px";
  8. divObj.style.height = "200px";
  9. divObj.style.backgroundColor = "red";
  10. })
  11. // jQuery
  12. $('#btn').click(() => {
  13. $('div').css({
  14. 'width': "200px",
  15. 'height': "200px",
  16. 'backgroundColor': "pink"
  17. })
  18. })
  19. </script>

jQuery中顶级对象$

  • DOM中的顶级对象:document——页面中的顶级对象
  • BOM中的顶级对象:window——-浏览器中的顶级对象
  • jQuery中的顶级对象:jQuery——$

$是jQuery的顶级对象,相当于原生JavaScript中的window。把元索利用$包装成Query对象,就可以调用jQuery的方法。
$是jQuery的别称,在代码中可以使用jQuery代替$,但一般为了方便,通常都直接使用$。

使用jQuery获取元素选择器为div的对象并隐藏

  1. $('div').hide(); //通过元素选择器获取div
  2. jQuery('div').hide();//通过元素选择器获取div

jQuery工厂函数$()的四种使用方式

  1. $(选择器,上下文) DOM选择,可以指定上下文;
  1. $('li').css('color','blue');
  2. $('li','#first').css('color','blue');
  3. // $('li','#first') === $('#first li')
  4. $('#first li').css('color','red');
  1. $(JS对象) jQuery包装器,将原生的js对象转为jQuery对象
    为什么要转换为jQuery对象,因为想使用jQuery对象上的非常丰富的方法和属性
  1. $(document.body).css('backgroundColor','lightgreen');
  2. console.log($(document.querySelectorAll('li')));
  1. $(html文本) 生成创建DOm元素
    用jQuery来创建DOM也是常见操作,例如在ul下创建一个li:
    $('<li>').appendTo($ul);

    1. document.body.insertAdjacentHTML('afterEnd','<p>晚上好!</p>');
    2. $('<p>hello world!</p>').appendTo( "body" );
    3. // 还可以更好玩
    4. $( "<div/>", {
    5. "class": "test",
    6. text: "Click me!",
    7. click: function() {
    8. $( this ).toggleClass( "test" );
    9. }
    10. }).appendTo( "body" );
  2. $(callback) DOM加载完成
    通常JavaScript需要在DOM加载完成后执行,否则DOM操作可能会失效。jQuery提供了一个方便的方法来监听DOM加载完成:

    1. $(function(){
    2. // DOM载入后执行
    3. });
    4. // $(callback)的作用完全相当于$(document).ready(callback)

总结$()的参数的四种类型:

  1. 选择器
  2. 原生JS对象(包装器功能)
  3. html字符串(创建dom元素)
  4. 回调函数(DOM加载完成自动调用)

jQuery对象和DOM对象

细说为什么要将jQuery对象和DOM对象进行互相转换,要想使用jQuery的方法和属性,就需要将其转换为jQuery的对象才能使用,但jQuery只是封装了一些好用的属性和方法,并不能完全代替JavaScript,这时候就可以将jQuery对象转换为原生的DOM对象,从而来完成一些特定的问题。

jquery对象转成DOM对象

DOM对象才能使用DOM方法,jquery对象不能使用DOM中的方法,但jquery对象提供了一套更加完善的工具用于操作DOM。

jQuery提供了两种方法:[index]和get(index)

  1. // 使用索引
  2. let div = $("div"); //jQuery对象
  3. console.log(div[0]); //DOM对象
  4. // 使用get(index)
  5. let div = $("div"); //jQuery对象
  6. console.log(div.get[0]); //DOM对象
  7. // 使用...rest
  8. console.log([...$('li')]); // jQuery对象转DOM对象

DOM对象转换为jquery对象

对于一个DOM对象,只需要用$()把DOM对象给包装起来,就可以获得一个jquery对象了,方式为$(DOM对象)。$(document.querySelector('div'))

  1. let btnObj = document.getElementById('btn');
  2. btnObj.onclick = function(){
  3. this.style.backgroundColor = 'red';
  4. }
  5. // DOM对象转JQuery对象
  6. $(btnObj).click(function(){
  7. $(this).css('backgroundColor','red');
  8. })


  1. // 原生JavaScript循环DOM元素
  2. document.querySelectorAll('li').forEach(function(item,key){
  3. console.log(key,item.textContent);
  4. })
  5. // jQuery自带遍历元素的,但也提供了each方法
  6. $.each($('li'),(key,item)=>{
  7. console.log(key,item.textContent);
  8. })

jQuery中常用的getter和setter方法

jQuery 的 setter/getter 共用一个函数,通过是否传参来表明它是何种意义。简单说传参它是 setter,不传它是 getter。即可以获取值也可以设置值

1. attr():获取/设置元素属性

attr()方法是jQuery中用于HTML属性的getter/setter。

  1. <input type="button" name="btn" value="显示效果" id="btn">
  1. // attr():获取和设置元素属性
  2. // attr(name):getter
  3. // attr(name,value):setter
  4. // removeAttr(name): 删除属性
  5. $('#btn').attr('type'); // button
  6. $('#btn').attr('value'); // "显示效果"
  7. $('#btn').attr('type','text'); // 修改成了文本框
  8. $('#btn').attr('value','我是一个文本框');
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>属性操作: attr()</title>
  8. <style>
  9. body {
  10. display: flex;
  11. flex-direction: column;
  12. align-items: center;
  13. background-color: lightcyan;
  14. font-weight: lighter;
  15. }
  16. #login {
  17. width: 400px;
  18. padding: 20px 10px;
  19. border: 1px solid #aaa;
  20. box-shadow: 0 0 5px #888;
  21. box-sizing: border-box;
  22. background-color: lightseagreen;
  23. color: #fff;
  24. display: grid;
  25. grid-template-columns: 80px 200px;
  26. gap: 10px;
  27. place-content: center center;
  28. }
  29. #login input {
  30. border: none;
  31. outline: none;
  32. }
  33. button {
  34. grid-column: 2 / 3;
  35. height: 32px;
  36. background-color: lightskyblue;
  37. border: none;
  38. outline: none;
  39. }
  40. button:hover {
  41. color: white;
  42. background-color: coral;
  43. color: #fff;
  44. /* border: none; */
  45. cursor: pointer;
  46. }
  47. .title {
  48. color: #666;
  49. font-weight: lighter;
  50. }
  51. </style>
  52. </head>
  53. <body id="main">
  54. <h2 class="title">用户登录</h2>
  55. <form action="handle.php" method="POST" id="login">
  56. <label for="email">Email:</label>
  57. <input type="email" name="email" id="email" autofocus placeholder="请输入邮箱" />
  58. <label for="password">Password:</label>
  59. <input type="password" name="password" id="password" placeholder="请输入密码" />
  60. <label for="confirm">记住我:</label>
  61. <div>
  62. <input type="radio" name="save" id="confirm" value="1" checked /><label for="confirm">保存</label>
  63. <input type="radio" name="save" id="cancel" value="0" /><label for="cancel">放弃</label>
  64. </div>
  65. <button>登录</button>
  66. </form>
  67. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  68. <script>
  69. // attr():获取和设置元素属性
  70. // attr(name):getter
  71. // attr(name,value):setter
  72. // removeAttr(name): 删除属性
  73. const form = $('form');
  74. // 获取action属性
  75. console.log(form.attr('action'));
  76. // 设置action属性
  77. form.attr('action','admin/check/php');
  78. console.log(form.attr('action'));
  79. // 第二个参数允许使用回调函数
  80. // 根据表单请求类型,动态设置不同处理脚本
  81. // get: action = query.php?id=2
  82. // post action = register.php
  83. form.attr('action',()=>{
  84. return form.attr('method').toLocaleLowerCase() === 'post'? ' register.php':'query.php?id=2';
  85. });
  86. console.log(form.attr('action'));
  87. // 删除标题的class属性
  88. $('h2').removeAttr('class');
  89. $('h2').attr('class');
  90. </script>
  91. </body>
  92. </html>

2. css():获取/设置元素的行内样式

css()方法和attr()方法很类似,只是css()方法作用于元素的css样式,而不是元素的HTML属性。

  1. // 使用style只能获取style属性上的行内样式
  2. // document.querySelector('#btn').style.width
  3. // css样式表的样式是获取不到的,必须使用计算样式才可以
  4. window.getComputedStyle(document.querySelector('#btn'),null).getPropertyValue('width');
  5. // 使用jQuery的css()方法 ,可以直接获得元素最终的计算样式
  6. $('#btn').css('width);
  7. // 设置一个属性样式
  8. $('#btn').css('backgroundColor','red');
  9. // 设置多个属性样式
  10. $('#btn').css({
  11. 'fontSize':'32px',
  12. 'color':'yellow',
  13. 'border':'0'
  14. })
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>行内样式操作: css()</title>
  8. <style>
  9. body {
  10. display: flex;
  11. flex-direction: column;
  12. align-items: center;
  13. background-color: lightcyan;
  14. font-weight: lighter;
  15. }
  16. #login {
  17. width: 400px;
  18. padding: 20px 10px;
  19. border: 1px solid #aaa;
  20. box-shadow: 0 0 5px #888;
  21. box-sizing: border-box;
  22. background-color: lightseagreen;
  23. color: #fff;
  24. display: grid;
  25. grid-template-columns: 80px 200px;
  26. gap: 10px;
  27. place-content: center center;
  28. }
  29. #login input {
  30. border: none;
  31. outline: none;
  32. }
  33. button {
  34. grid-column: 2 / 3;
  35. height: 32px;
  36. background-color: lightskyblue;
  37. border: none;
  38. outline: none;
  39. }
  40. button:hover {
  41. color: white;
  42. background-color: coral;
  43. color: #fff;
  44. /* border: none; */
  45. cursor: pointer;
  46. }
  47. .title {
  48. color: #666;
  49. font-weight: lighter;
  50. }
  51. </style>
  52. </head>
  53. <body id="main">
  54. <h2 class="title">用户登录</h2>
  55. <form action="handle.php" method="POST" id="login">
  56. <label for="email">Email:</label>
  57. <input type="email" name="email" id="email" autofocus placeholder="请输入邮箱" />
  58. <label for="password">Password:</label>
  59. <input type="password" name="password" id="password" placeholder="请输入密码" />
  60. <label for="confirm">记住我:</label>
  61. <div>
  62. <input type="radio" name="save" id="confirm" value="1" checked /><label for="confirm">保存</label>
  63. <input type="radio" name="save" id="cancel" value="0" /><label for="cancel">放弃</label>
  64. </div>
  65. <button>登录</button>
  66. </form>
  67. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  68. <script>
  69. // css() : 包括了行内样式的计算样式
  70. // css(name):getter
  71. // css(name,value):setter
  72. // css(name,callback)
  73. // 原生操作css
  74. console.log(document.querySelector('form').style.width); // 只能获取行内样式
  75. console.log(window.getComputedStyle(document.querySelector('form'),null).getPropertyValue('width')); // 获取计算样式
  76. // jQuery
  77. const form = $('#login');
  78. // css可以直接获取到元素的计算样式
  79. console.log(form.css('width'));
  80. // 设置样式
  81. // form.css('border-top','5px solid yellow');
  82. // form.css('border-bottom','5px solid yellow');
  83. form.css({
  84. 'border-top':'5px solid yellow',
  85. 'border-bottom':'5px solid yellow'
  86. });
  87. // 表单的背景色随机变换
  88. form.css('background',()=>{
  89. const colors = ['lightpink','lightblue','lime','wheat','lightgreen'];
  90. return colors[Math.floor(Math.random()*colors.length)];
  91. })
  92. </script>
  93. </body>
  94. </html>

3. addClass()和removeClass() 添加和删除类

addClass()方法用来从选中元素中添加类样式
removeClass()方法用来从选中元素中和删除类样式
hasClass()方法用来从选中的元素中判断某类是否存在
toggleClass()方法当元素还没有某些类时,给元素添加这些类;反之,则删除。

  1. $('#btn').addClass('btn'); // 添加类
  2. $('#btn').hasClass('btn'); // true
  3. $('#btn').removeClass('btn'); // 删除类
  4. $('#btn').hasClass('btn'); // false
  5. $('#btn').toggleClass('btn'); // 切换类 添加/删除
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>class操作</title>
  8. <style>
  9. .title {
  10. color: red;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <h1 class="title">php.cn</h1>
  16. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  17. <script>
  18. // 原生: classList对象
  19. // let h1 = document.querySelector("h1");
  20. // 添加class
  21. // h1.classList.add("title");
  22. // 移除class
  23. // h1.classList.remove("title");
  24. // 切换class
  25. // h1.classList.toggle("title");
  26. // -------------------------------
  27. // jquery
  28. // addClass() => classList.add()
  29. // removeClass() => classList.remove()
  30. // toggleClass() => classList.toggle()
  31. const h1 = $("h1");
  32. h1.addClass("title");
  33. h1.removeClass("title");
  34. h1.toggleClass("title");
  35. </script>
  36. </body>
  37. </html>

4. val() 获取表单元素的值(value)

val()方法用来设置和获取HTML表单元素的value属性,还可用于获取和设置复选框、单选按钮以及<select>元素的选中状态。

  1. // 原生获取
  2. document.getElementById('btn').value;
  3. $('#btn').val(); // 显示效果
  1. // val():无参,默认就是获取控件元素(input,select...)的value属性的值
  2. // val(param): 设置
  3. // val(callback)
  4. // 原生
  5. document.forms.login.email.value = "admin@qq.com";
  6. console.log(document.forms.login.email.value);
  7. // jquery
  8. console.log($("#email").val());
  9. // $("#password").val("123456");
  10. $("input:password").val("123456");
  11. console.log($("input:password").val());
  12. console.log($("input:radio:checked").val());
  13. $("#email").val(() => "zhang@qq.com");

5. text()和html():获取/设置元素内容

text()和html()方法用来获取和设置元素的纯文本或HTML内容

  1. <ul>
  2. 列表
  3. <li class="item1">item1</li>
  4. <li class="item2">item2</li>
  5. <li class="item3">item3</li>
  6. <li class="item4">item4</li>
  7. </ul>
  8. <script>
  9. $(function(){
  10. // 获取
  11. $('ul').text(); // "列表" 获取纯文本
  12. $('ul').html();
  13. /*
  14. 列表
  15. <li>item1</li>
  16. <li>item2</li>
  17. <li>item3</li>
  18. <li>item4</li>
  19. */
  20. $('ul .item2').text(); // item2
  21. // 设置
  22. $('ul').text("你好");
  23. $('ul').html(`
  24. <li>item1</li>
  25. <li>item2</li>
  26. <li>item3</li>
  27. <li>item4</li>
  28. <li>item5</li>
  29. <li>item6</li>
  30. `);
  31. })
  32. </script>
  1. // text(): 读/写入文本, textContent
  2. // html(): 读/写html文本, innerHTML
  3. $(".box").text("hello world");
  4. // text()不能解析文本中的html,转为实体字符原样输出
  5. $(".box").text("<strong style='color:red'>hello world</strong>");
  6. // html()
  7. $(".box").html("<strong style='color:red'>hello world</strong>");

更多相关文章

  1. 面向对象、类和对象、封装---------私有private、this关键字
  2. css实现垂直居中的方式
  3. 如果使用的库不支持异步,可以使用多进程并将其转化为异步对象
  4. 一个可能让你的页面渲染速度提升数倍的CSS属性
  5. 一些鲜为人知的的CSS3属性
  6. css 中的 content-visitly 提升渲染性能
  7. 关于获取各种浏览器可见窗口大小的一点点研究
  8. javascript创建对象几种方式
  9. 前端170面试题+答案学习整理

随机推荐

  1. (C++)错误的map删除操作和STL中容器的迭代
  2. 第一章C++:函数返回值、GNU编译器命令
  3. 案例分享c++ map的使用和 查找性能测试
  4. C++引用的意义与引用的本质
  5. 从事C/C++开发多年,给零基础想学习C/C++的
  6. C++ 布尔类型和引用的用法详解
  7. C语言不简单,连程序员都这么说,为什么呢?
  8. C#引用类型: 按值传递,按引用传递的对比
  9. C++中的四种强制类型转换_基本用法及使用
  10. 探索C++虚函数在g++中的实现(动多态)_虚函