Blogger Information
Blog 32
fans 0
comment 0
visits 22275
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
jQuery 浅析
培(信仰)
Original
529 people have browsed it

jQuery 浅析(操作 dom,过滤器,事件,jQuery-Ajax,jq-留言板)

操作 dom()

由于 append/appendTo 只能追加到最后一个,感觉没有原生的灵活。
不过删除比较方便,获取元素直接 remove()

  1. //1. 添加元素
  2. // const h2 = document.createElement("h2");
  3. // h2.textContent = "你好吗?要开心哦。";
  4. // document.body.appendChild(h2);
  5. // document.body.insertAdjacentHTML("beforeend","<h2>你要坚强哦。加油!</h2>");
  6. // document.body.insertAdjacentElement("beforeend",h2);
  7. // const flg = document.createDocumentFragment();
  8. // const h2 = document.createElement("h2");
  9. // h2.textContent = "这是h2";
  10. // const h3 = document.createElement("h3");
  11. // h3.textContent = "这是h3";
  12. // flg.appendChild(h2);
  13. // flg.appendChild(h3);
  14. // document.body.appendChild(flg);
  15. // 使用 jQuery 要先生成元素
  16. // $('<h2>要过年了,都准备好了吗?</h2>').appendTo($('body'));
  17. $("<h3>").text("这是在子元素上调用的appendTo").appendTo($("body"));
  18. // 子元素.appendTo(父元素)
  19. $("body").append("<h2>这是在父元素上调用的append</h2>");
  20. // $("body")
  21. // .append("<ol></ol>")
  22. // .append(() => {
  23. // let str = "";
  24. // for (let i = 0; i < 5; i++) {
  25. // str += `<li><a>新品赏识:商品 ${i + 1}</a></li>`;
  26. // }
  27. // return str;
  28. // });
  29. $("body").append("<ol></ol>");
  30. // $("body").append("<ol></ol>") 返回的是body 因为是在body上的操作
  31. const ol = $("ol");
  32. // 此时append() 与 html() 功能是一样的
  33. ol.append(() => {
  34. let str = "";
  35. for (let i = 0; i < 5; i++) {
  36. str += `<li><a>新品上市:商品 ${i + 1}</a></li>`;
  37. }
  38. return str;
  39. });
  40. console.log($("li:first-of-type"));
  41. // $(("li:first-of-type")).remove();
  42. // 如果用其他元素替代则是覆盖,不会复制后覆盖。
  43. // $("li:nth-of-type(2)").replaceWith($("li:nth-of-type(3)"));

效果图

过滤器

这个过滤器不知道有什么应用场景,通过选择器也可以获得元素。
不过这find()很好用

  1. <body>
  2. <ul id="first">
  3. <li>item1</li>
  4. <li>
  5. item2
  6. <ul>
  7. <li>1</li>
  8. <li class="red">2</li>
  9. <li>3</li>
  10. <li>4</li>
  11. <li>5</li>
  12. </ul>
  13. </li>
  14. <li>item3</li>
  15. <li>item4</li>
  16. <li>item5</li>
  17. </ul>
  18. <ul id="second">
  19. <li>item1</li>
  20. <li>item2</li>
  21. <li>item3</li>
  22. <li>item4</li>
  23. <li>item5</li>
  24. </ul>
  25. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
  26. <script>
  27. console.log($("ul#first"));
  28. $("ul#first").css("background", "skyblue");
  29. console.log($("ul").filter("#first").children());
  30. $("ul").filter("#first").children().css("color", "blue");
  31. console.log($("ul").filter("#first").children().first().text());
  32. console.log($("ul").filter("#first").children().last().text());
  33. // jq只要第2个
  34. console.log($("ul").filter("#first").children().eq(1).text());
  35. // find(): 可以获取任意层级的元素(包括子元素)
  36. // children():方法只获取子元素集合
  37. console.log($("ul").filter("#first").children(".red"));
  38. // 结果没有找到
  39. $("ul").filter("#first").find(".red").css("background", "red");
  40. //jq + 原生
  41. $("#first .red")[0].style.background = "pink";
  42. console.log("---------------");
  43. //原生
  44. console.log(document.getElementById("second").children);
  45. document.getElementById("second").firstElementChild.style.color = "red";
  46. document.getElementById("second").lastElementChild.style.color = "red";
  47. document.getElementById("second").children[1].style.color = "blue";
  48. console.log(document.getElementById("second").lastChild);
  49. console.log(document.getElementById("second").lastElementChild.textContent);
  50. console.log(document.getElementById("second").children[1].textContent);
  51. console.log(document.getElementById("second").children.item(1).textContent);
  52. </script>
  53. </body>

效果图

事件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>事件</title>
  7. <style>
  8. form {
  9. display: grid;
  10. padding: 1em;
  11. width: 15em;
  12. gap: 1em;
  13. border: 1px solid blue;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <form action="check.php">
  19. <label>用户登录</label>
  20. <input type="text" name="username" placeholder="UserName" autofocus />
  21. <input type="password" name="password" placeholder="Password" />
  22. <button>Submit</button>
  23. </form>
  24. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
  25. <script>
  26. // 禁用表单的默认提交行为
  27. // document.querySelector("form").onsubmit = ev => ev.preventDefault();
  28. //jq
  29. $("form").submit((ev) => ev.preventDefault());
  30. //表单验证
  31. //验证用户名:如果为空提示不能为空,如果用户名已存在,提示用户重新填写
  32. const user = $('input[name="username"]');
  33. // 在失去焦点的时候进行验证
  34. user.blur(function () {
  35. // 如果使用this关键字就不能用箭头函数,此处如果使用箭头函数 this指向window
  36. // 提示信息
  37. let tips = "";
  38. // 用户列表
  39. const users = ["admin", "user", "root"];
  40. if ($(this).val().length === 0) {
  41. tips = "用户名不能为空";
  42. $(this).focus();
  43. } else if (users.indexOf($(this).val()) === -1) {
  44. tips = "用户不存在,请注册" + "<button>注册</button>";
  45. } else {
  46. tips = '<i style="color:green">用户名正确</i>';
  47. }
  48. if ($(this).next()[0].tagName !== "SPAN") {
  49. $("<span></span>")
  50. .html(tips)
  51. .css("color", "red")
  52. .insertAfter($(this));
  53. }
  54. });
  55. // user.on("input", () => $("span").remove());
  56. user.on("input", function () {
  57. $(this).next("span").remove();
  58. });
  59. </script>
  60. </body>
  61. </html>

jQuery 的事件感觉要比原生的好记忆,可能初学还没有大量实战感觉有误。就是编辑器对 on()里面的语法提示没有,需要查文档,不是很方便。

jQuery-Ajax 这个有点意思

配置环境:开启虚拟环境,创建站点并新建 info.php;创建另外一个站点,并新建 users.php

info.php

  1. <?php
  2. //info.php
  3. header('content-type:text/html;charset=utf-8');
  4. //获取回调名称
  5. $callback = $_GET['jsonp'];
  6. $id = $_GET['id'];
  7. //模拟接口数据
  8. $users = [
  9. 0 =>'{"name":"朱老师","email":"peter@php.cn"}',
  10. 1 =>'{"name":"西门","email":"xm@php.cn"}',
  11. 2 =>'{"name":"灭绝","email":"mj@php.cn"}'
  12. ];
  13. if (array_key_exists(($id-1), $users)) {
  14. $user = $users[$id-1];
  15. }
  16. // 动态生成handle()的调用
  17. echo $callback . '(' . $user . ')';

users.php

  1. <?php
  2. //users.php
  3. //二维数组来模拟数据表的查询结果
  4. $users = [
  5. ['id' => 1,'name' => '天蓬大人','age' => '55'],
  6. ['id' => 2,'name' => '灭绝师太','age' => '22'],
  7. ['id' => 3,'name' => '西门老妖','age' => '44'],
  8. ];
  9. //$_REQUEST:相当于$_GET + $_POST + $_COOKIE 三合一
  10. if (in_array($_REQUEST['id'], array_column($users, 'id'))) {
  11. foreach ($users as $user) {
  12. if ($user['id'] == $_REQUEST['id']) {
  13. //vprintf(输出模板,数组表示的参数)
  14. vprintf('%s; %s %s岁', $user);
  15. // 以下语句配合$.getJOSN()调用,其他请求时请注释掉
  16. // echo json_encode($user);
  17. }
  18. }
  19. } else {
  20. die('<span style="color:red">没找到</span>');
  21. }

html 实现

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>jQuery-Ajax</title>
  7. <style>
  8. body {
  9. display: grid;
  10. gap: 2em;
  11. padding: 2em;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <button class="get">1. $.get() 请求数据</button>
  17. <button class="post">2. $.post() 请求数据</button>
  18. <button class="jsonp">3. $.ajax():JSONP 跨域请求数据</button>
  19. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
  20. <script>
  21. // 1. $.get(url,QueryString,callback)
  22. // console.log($('.get'));
  23. $("button:first-of-type").click(function (ev) {
  24. // $.get('users.php?id=1',function (data){
  25. $.get("users.php", { id: 2 }, function (data) {
  26. // console.log(data);
  27. //站在触发的对象上思考
  28. // $(ev.target).after("<div></div>").next().html(data);
  29. //站在要添加的对象上思考
  30. $("<div></div>")
  31. .html(data)
  32. .css("color", "pink")
  33. .insertAfter($(ev.target));
  34. // console.log($(ev.target));
  35. });
  36. });
  37. // 2. post()
  38. $(".post").click(function (ev) {
  39. $.post("users.php", { id: 3 }, function (data) {
  40. $("<div></div>")
  41. .html(data)
  42. .css("color", "pink")
  43. .insertAfter($(ev.target));
  44. });
  45. });
  46. // 3. jsonp $.ajax()
  47. // $.ajax({
  48. // type:'get',
  49. // url: 'users.php',
  50. // data: {id: 2},
  51. // dataType: 'html',
  52. // success: function () {
  53. // }
  54. // })
  55. $(".jsonp").click(function (ev) {
  56. $.ajax({
  57. type: "get",
  58. url: "http://world.io:8088/info.php?id=2&jsonp=?",
  59. // data: { id: 2},
  60. dataType: "jsonp",
  61. // 告诉跨域访问的服务器需要返回的函数名称
  62. jsonpCallback: "show",
  63. });
  64. });
  65. function show(data) {
  66. console.log(data);
  67. $(".jsonp")
  68. .after("<div></div>")
  69. .next()
  70. .html(`${data["name"]} ${data.email}`);
  71. }
  72. </script>
  73. </body>
  74. </html>

总结:
$.get('users.php?id=1',function (data){}
$.get("users.php", { id: 2 }, function (data) {}

  1. $(".jsonp").click(function (ev) {
  2. $.ajax({
  3. type: "get",
  4. url: "http://world.io:8088/info.php?id=2&jsonp=?",
  5. // data: { id: 2},
  6. dataType: "jsonp",
  7. // 告诉跨域访问的服务器需要返回的函数名称
  8. jsonpCallback: "show",
  9. });
  10. });

语法需要记忆

jQuery实现一个留言板

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>留言板</title>
  7. <link rel="stylesheet" href="./iconfont/icon-font/iconfont.css" />
  8. <style>
  9. * {
  10. margin: 0;
  11. padding: 0;
  12. box-sizing: border-box;
  13. font-size: 10px;
  14. }
  15. ul,
  16. li {
  17. list-style: none;
  18. }
  19. .box {
  20. width: 50rem;
  21. height: 10rem;
  22. margin: 1rem auto;
  23. }
  24. h2 {
  25. font-size: 3rem;
  26. display: flex;
  27. justify-content: center;
  28. margin-bottom: 1rem;
  29. }
  30. .message {
  31. display: flex;
  32. flex-flow: column nowrap;
  33. width: 100%;
  34. }
  35. .message textarea {
  36. width: 100%;
  37. min-height: 10rem;
  38. padding: 0.6rem 1rem;
  39. border: 1px solid #c9c9c9;
  40. border-radius: 2px;
  41. outline: none;
  42. font-size: 1.4rem;
  43. }
  44. .message .button {
  45. width: 100%;
  46. height: 5rem;
  47. margin-top: 1rem;
  48. }
  49. .message .button .btn {
  50. padding: 0 2rem;
  51. height: 3.5rem;
  52. border-radius: 3px;
  53. border-width: 0;
  54. font-size: 1.2rem;
  55. outline: none;
  56. cursor: pointer;
  57. }
  58. .message .button .btn:hover {
  59. transition: all 0.3s;
  60. opacity: 0.8;
  61. }
  62. .message .button .btn.btn-submit {
  63. background-color: #3e7777;
  64. color: #fff;
  65. }
  66. .message .button .btn.btn-reset {
  67. margin-left: 0.5rem;
  68. }
  69. .message .content-wrap em.tips {
  70. color: red;
  71. margin-top: 1rem;
  72. }
  73. .list {
  74. width: 100%;
  75. display: grid;
  76. grid-template-columns: 1fr;
  77. grid-template-rows: auto;
  78. margin-top: 1rem;
  79. }
  80. .list li {
  81. display: grid;
  82. grid-template-columns: 4rem 1fr;
  83. grid-template-rows: auto auto;
  84. gap: 0.5rem;
  85. margin-top: 1rem;
  86. }
  87. .list li.item .avatar {
  88. width: 4rem;
  89. height: 4rem;
  90. }
  91. .list li.item .avatar .iconfont.icon-my {
  92. font-size: 4em;
  93. border-radius: 50%;
  94. color: #3e7777;
  95. }
  96. .list li.item .comment {
  97. display: grid;
  98. grid-template-columns: 1fr;
  99. row-gap: 0.5rem;
  100. }
  101. .list li.item .comment .title {
  102. display: flex;
  103. flex: rows nowrap;
  104. align-items: center;
  105. }
  106. .list li.item .comment .title .nick > * {
  107. font-size: 1.6rem;
  108. color: #000;
  109. }
  110. .list li.item .comment .title .time {
  111. color: #8c92a4;
  112. margin-left: 0.5rem;
  113. font-size: 1.2rem;
  114. font-size: 1.4rem;
  115. }
  116. .list li.item .comment .context {
  117. color: #40485b;
  118. font-size: 1.4rem;
  119. margin: 0.5rem 0;
  120. }
  121. .list li.item .del {
  122. margin: 0.5rem 0;
  123. display: grid;
  124. cursor: pointer;
  125. border: none;
  126. place-self: center end;
  127. grid-area: 2 / 1 / 2 / 3;
  128. padding: 0.5rem;
  129. outline: none;
  130. }
  131. hr {
  132. border-color: rgba(222, 222, 222, 0.5);
  133. }
  134. </style>
  135. </head>
  136. <body>
  137. <div class="box">
  138. <h2>留言板</h2>
  139. <div class="message">
  140. <div class="content-wrap">
  141. <textarea
  142. name="message"
  143. class="content"
  144. placeholder="请输入内容"
  145. cols="30"
  146. rows="10"
  147. ></textarea>
  148. <em class="tips" style="display: none">* 留言内容不能为空。</em>
  149. </div>
  150. <div class="button">
  151. <button class="btn btn-submit">提交</button>
  152. <button class="btn btn-reset" type="reset">重置</button>
  153. </div>
  154. </div>
  155. <hr />
  156. <ul class="list"></ul>
  157. </div>
  158. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
  159. <script>
  160. const msg = $(".content");
  161. const btnSubmit = $(".btn-submit");
  162. const btnReset = $(".btn-reset");
  163. const ul = $(".list");
  164. btnSubmit.click((ev) => {
  165. let str = `<li class="item">
  166. <div class="avatar">
  167. <span class="iconfont icon-my"></span>
  168. </div>
  169. <div class="comment">
  170. <div class="title">
  171. <span class="nick">
  172. <b>游客</b>
  173. </span>
  174. <div class="time">${formatDate(Date.now())}</div>
  175. </div>
  176. <div class="context">${msg.val()}</div>
  177. <hr>
  178. </div>
  179. <button class="del" >删除</button>
  180. </li>`;
  181. //onclick="del(this)"
  182. if (msg.val().length === 0) {
  183. $(".tips").css("display", "block");
  184. return false;
  185. }
  186. // ul.append(str);
  187. ul[0].insertAdjacentHTML("afterbegin", str);
  188. msg.val(null);
  189. });
  190. msg.on("input", (ev) => {
  191. $(".tips").css("display", "none");
  192. });
  193. btnReset.click((ev) => {
  194. msg.val(null);
  195. });
  196. ul.on("click", function (ev) {
  197. if (ev.target.className === "del") {
  198. // console.log(ev.target.parentNode);
  199. confirm("是否删除?") ? ev.target.parentNode.remove() : false;
  200. }
  201. });
  202. // function del(ev) {
  203. // ev.parentNode.remove();
  204. // }
  205. // 获取时间
  206. function formatDate(time) {
  207. let date = new Date(time);
  208. let y = date.getFullYear();
  209. let m = date.getMonth()+1;
  210. let d = date.getDate();
  211. let h = date.getHours();
  212. let mi = date.getMinutes();
  213. let s = date.getSeconds();
  214. return `${y}-${m}-${d} ${h}:${mi}:${s}`;
  215. }
  216. </script>
  217. </body>
  218. </html>


总结:jq对象转成js对象,或者js对象转jq对象将会有更大的灵活性。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post