PHP 学习之路:第十六天—— jQuery 函数与常用方法

176 阅读2分钟

一、jQuery 导入

image.png

<!-- 本地导入 -->
<script src="jquery-3.6.0.js"></script>

image.png

<!-- cdn引入 -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

二、jQuery 基础知识

1.jQuery是什么?

// 1. jQuery是什么?
// jQuery 是一个工厂函数
// jquery中所有操作, 都是通过一个叫"jQuery"的函数来完成的
console.log(jQuery);
console.log(typeof jQuery);     

2. $ 是 jQuery 函数的别名

// 2. $ 是 jQuery 函数的别名
// 如果你的项目中, $ 没有被占用
// let $;
// 你可以用 $ 来直接引用 jQuery
// let $ = jQuery;
// console.log($ === jQuery);

console.log($);
// $ 已经在jQuery的底层封装好了,直接用就可以了

3. jQuery与原生对比

// 3. jQuery与原生对比:jQuery 写得少, 干得多
// body 换背景色
// 原生
document.body.style.backgroundColor = "yellow";

// jQuery
// $("body").css("background-color", "lightgreen");
$("body").css("backgroundColor", "lightgreen");

4. jQuery语法

// 4. jQuery语法
// 场景1: 当成函数用, 创建jQuery对象
$("<h3>Hello 晚上好</h3>").css("color", "red").appendTo("body");

// $(参数).method1().method2()....,链式调用,对jQuery对象集合中的每个成员进行回调操作
// $(selector).m1().m2()....

// 场景2: 函数也是对象,所以可以将函数当成对象来用
// let fn = () => {};
// fn既是函数,也是对象,既然是对象,就可以拥有属性
// fn.email = "a@qq.com";
// console.log(fn.email);
// $.ajax, $.get, $.post

三、细说 $()

案例 html 结构:

<ul class="list">
  <li class="item">item1</li>
  <li class="item">item2</li>
  <li class="item">item3</li>
  <li class="item">item4</li>
  <li class="item">item5</li>
</ul>

1. $(选择器, 上下文)

// 1. $(选择器, 上下文): 获取dom元素
// 将所有li前景色更新成红色
// 原生
document.querySelectorAll(".list .item").forEach((item) => (item.style.color = "red"));

// jQuery
console.log($(".item", ".list"));
$(".item", ".list").css("color", "green");
// 第二参数上下文完全可以用第一个参数来模拟
$(".list .item").css("color", "blue");

2. $(js原生对象)

// 2. $(js原生对象): 将原生js对象转换jQuery对象,也叫"包装"成jQuery对象
// 这时,这个$()也有一个名称:  包装器
//   document.body.css("background-color", "yellow");
$(document.body).css("background-color", "yellow");
console.log($(document.body) instanceof jQuery);

3. $(html文本)

// 3. $(html文本): 创建dom元素,直接包装成jQuery对象返回
// const p = document.createElement("p");
// p.textContent = "Hello World";
// document.body.prepend(p);
document.body.insertAdjacentHTML("afterbegin", "<p>哈哈,我还没有吃晚饭</p>");
$("<p>同志们,辛苦了</p>").insertAfter(".list");

4. $(回调)

// 4. $(回调): dom树一旦创建完成,就会立即执行这个回调
// $("body h2").css("color", "red");
$(() => {
$("body h2").css("color", "red");
});

四、jQuery 对象与 js 原生对象之间的转换

案例 html 结构:

<ul class="list">
  <li class="item">item1</li>
  <li class="item">item2</li>
  <li class="item">item3</li>
  <li class="item">item4</li>
  <li class="item">item5</li>
</ul>

因为 jQuery 的局限性,很多场景下需要将 jQuery 对象转为 js 原生对象来调用 js 功能完成操作

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

<script>
  // 因为jQuery的局限性,很多场景下需要将jQuery对象转为js原生对象来调用js功能完成操作

  console.log($(".list .item"));
  // 任何一个$()返回的都是一个jQuery集合对象
  // 整体集合是一个JQuery对象,但是集合中的每个成员却是原生的js对象
  console.log($(".list .item")[0]);

  // 第一个li本身就是原生js对象
  $(".list .item")[0].style.backgroundColor = "yellow";
  // 也可以使用jQuery封装的另一个方法
  $(".list .item").get(2).style.backgroundColor = "lightgreen";

  // 既然整体返回的是一个jQuery对象,那我能不能将整个jQuery转成原生js用
  // 将整个ul当成js原生对象
  console.log($(".list"));
  console.log($(".list")[0]);
  $(".list")[0].style.border = "2px solid";
</script>

五、常用的操作

案例 html 结构:

<body id="main">
  <h2 class="title">用户登录</h2>
  <form action="handle.php" method="POST" id="login">
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" autofocus placeholder="leture@php.cn" />
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" placeholder="不少于6位" />
    <label for="confirm">记住我:</label>
    <div>
      <input type="radio" name="save" id="confirm" value="1" checked />
      <label for="confirm">保存</label>
      <input type="radio" name="save" id="cancel" value="0" />
      <label for="cancel">放弃</label>
    </div>
    <button>登录</button>
  </form>
</body>

案例 css 样式:

body {
display: flex;
flex-direction: column;
align-items: center;
background-color: lightcyan;
font-weight: lighter;
}

#login {
width: 400px;
padding: 20px 10px;
border: 1px solid #aaa;
box-shadow: 0 0 5px #888;
box-sizing: border-box;
background-color: lightseagreen;
color: #fff;
display: grid;
grid-template-columns: 80px 200px;
gap: 10px;
place-content: center center;
}

#login input {
border: none;
outline: none;
}

button {
grid-column: 2 / 3;
height: 32px;
background-color: lightskyblue;
border: none;
outline: none;
}

button:hover {
color: white;
background-color: coral;
color: #fff;
/* border: none; */
cursor: pointer;
}

.title {
color: #666;
font-weight: lighter;
}

1. 属性操作: attr()

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
  // console.log($("body").attr("id"));

  // attr():获取/设置元素属性
  // attr(name):getter
  // attr(name,value): setter
  // removeAttr(name): 删除属性

  const form = $("form");
  // 获取
  console.log(form.attr("action"));
  // 设置
  form.attr("action", "admin/check.php");
  console.log(form.attr("action"));

  // 第二个参数允许使用回调

  // 根据表单的请求类型, 动态设置不同的处理脚本
  // get: action = query.php?id=2
  // post: action = register.php

  form.attr("action", () => {
    return form.attr("method").toLocaleLowerCase() === "post" ? "register.php" : "query.php?id=2";
  });
  console.log(form.attr("action"));

  // 删除属性
  $("h2").removeAttr("class");
</script>

2.行内样式操作: css()

<script>
  // css(): 包括了行内样式的计算样式
  // css(name): getter
  // css(name,value): setter
  // css(name,callback)

  // 原生
  console.log(document.querySelector("form").style.width);
  console.log(window.getComputedStyle(document.querySelector("form"), null).getPropertyValue("width"));

  // jquery
  const form = $("#login");
  // css()可以直接获取到计算样式
  console.log(form.css("width"));

  form.css("border-top", "5px solid yellow");
  // css(obj), 同时设置多个样式声明
  form.css({
    "border-bottom": "5px solid #000",
    background: "green",
  });

  // css(name,callback)
  // 表单的背景色随机变换
  form.css("background", () => {
    const colors = ["lightpink", "lightblue", "lime", "wheat"];
    // 生成一个随机的数组下标, 0 - 3之间

    return colors[Math.floor(Math.random() * colors.length)];
  });
</script>

3.表单控件的值: val()

// val():无参,默认就是获取控件元素(input,select...)的value属性的值
// val(param): 设置
// val(callback)

// 原生
document.forms.login.email.value = "admin@qq.com";
console.log(document.forms.login.email.value);

// jquery
console.log($("#email").val());
// $("#password").val("123456");
$("input:password").val("123456");
console.log($("input:password").val());

console.log($("input:radio:checked").val());

$("#email").val(() => "朱老师@php.cn");

4. text(), html()

<div class="box"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

<script>
  // text(): 读/写入文本, textContent
  // html(): 读/写html文本, innerHTML

  $(".box").text("hello world");
  // text()不能解析文本中的html,转为实体字符原样输出
  $(".box").text("<strong style='color:red'>hello world</strong>");

  // html()
  $(".box").html("<strong style='color:red'>hello world</strong>");
</script>

5. class操作

<style>
  .title {
    color: red;
  }
</style>
<h1>php.cn</h1>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
  // 原生: classList对象
  let h1 = document.querySelector("h1");
  h1.classList.add("title"); // 添加class
  h1.classList.remove("title"); // 移除class
  h1.classList.toggle("title"); // 切换class

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

  // jquery
  // addClass() => classList.add()
  // removeClass() => classList.remove()
  // toggleClass() => classList.toggle()
  const h1 = $("h1");
  h1.addClass("title");
  h1.removeClass("title");
  h1.toggleClass("title");
</script>