jquery的进阶


typora-copy-images-to: images
typora-root-url: images

DOM操作

操作类别

• 插入 删除 复制 替换 查找

1、内部插入

插入图解:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GgsJRyxV-1663214062830)(/1565492529293.png)]

标签内部最后面

$(selector).append(content) :将content移动(追加)到selector内部的最后面

content.appendTo($(selector)):将content移动到selector内部的最后面

content.prependTo($(selector)) 将元素追加到selector内部的最前面

$(selector).prepend(content) :将content移动(追加)到selector内部的最前面

    <button id="prepend">prepend </button>
     <button id="append">append</button>
   <script>
    $(function(){
        $('#prepend').click(function(){
            var li = $("<li></li>");
            li.html(Math.random());
            li.prependTo('#box');
        });

        $('#append').click(function(){
            var li = $('<li></li>');
             li.html('come on');
           //  li.appendTo('#box');
            $('#box').append(li);
        });
    });
2、外部插入

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m68hYraW-1663214062831)(/1565492954389.png)]

标签外部后面

l $(selector).after(content) :将content移动到selector选择器外部的最后面

l content.insertAfter($(selector)) :将content移动到selector选择器外部的最后面

标签外部前面

l $(selector).before(content) :将content移动到selector选择器外部的最前面

l content.insertBefore($(selector)) :将content移动到selector选择器外部的最前面

  <ul id="box">
        <li>张三</li>
        <li>李四</li>
    </ul>
    <button id="before">before </button>
     <button id="after">after</button>
   <script>
    $(function(){
        $('#before').click(function(){
            var li = $("<li></li>");
            li.html(Math.random());
          // li.insertBefore('#box');
          $('#box').before(li)
        });
        
      $('#after').click(()=>{
          var li = $('<li></li>');
          li.html(Math.random());
          //li.insertAfter('#box');
          $('#box').after(li)
      });
    });
    </script>
案例: 实时的录入数据

知识点提要

val() 获取input的value值
clone() 克隆一个节点
 $(":text") 获取type类型为text的input框
<table id="box" rules="all" width="500" height="200" border="1" cellpaadding="0" cellspacing="0">
    <thead>
		<tr>
			<th>编号</th>
			<th>姓名</th>
			<th>性别</th>
		</tr>
	</thead>
	<tbody id="content">
		<tr>
			<td>1</td>
			<td>张三</td>
			<td>22</td>
		</tr>
		<tr>
			<td>2</td>
			<td>李四</td>
			<td>20</td>
		</tr>
		<tr>
			<td>3</td>
			<td>王五</td>
			<td>18</td>
		</tr>
	</tbody>
</table>
<input type="text" id="num">
<input type="text" id="user">
<input type="text" id="age">
<button id="btn">增加</button>

<script>
    	$(function(){
		$("#btn").click(function(){
			//获取输入框中的值
			var num=$("#num").val();
			var user=$("#user").val();
			var age=$("#age").val();
			//克隆一行tr
			var tr=$("tbody tr").eq(0).clone();
			//将输入框中的值放到td中
			tr.find("td").eq(0).html(num);
			tr.find("td").eq(1).html(user);
			tr.find("td").eq(2).html(age);
			//将新增的一行放在表格中
			$("#content").append(tr);
			//清空输入框中的值
			$(":text").val("");
		})
	})
</script>

[重点]文本和值的操作

基本用法:

l 非表单元素(如:div、span、p、h1-h5、li、button等):

html() : 获取标签的内容(内容包括标签) .innerHTML

html(text/html) : 设置标签中的内容 .innerHTML = ‘ ’

text() : 获取标签的文本内容。

text(text) : 设置标签的文本内容

l 表单元素(input、select、radio、checkbox、textarea等):

val() : 获取value属性值 .value

val(val) : 设置value属性值 .value = ‘ ’

案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="box">
       <p>这是div元素</p>
    </div>
    <p>张三</p>
    <p>李四</p>
    <input type="text" name="user" value="张三">
    <script src="./jquery-2.2.4.js"></script>

    <script>
      console.log($('#box').html())
      console.log($('#box').text());

      console.log($('p:last').text());
      console.log($('p:last').text('唢呐声声'));

      console.log($("input[name='user']").val());
      console.log($("input[name='user']").val('你大爷'));
    </script>
</body>
</html>

[重点]遍历

回顾:js中的遍历

数组的遍历

for()

forEach()

对象的遍历

for(var key in obj)

for-of

jQuery中的each方法介绍

each()方法:作用:主要用来循环jquery对象或数组。

语法:

推荐写法:

$.each(jquery对象或数组,function(k,v){
// to do ...
});
或者下面这样写
jquery对象.each(function(k,v){
// to do ...
});

脚下留心

被遍历处理的v是一个DOM对象,不能直接调用Jquery的方法,需要转化为jq对象 $(v)

Obj是要遍历的对象或者数组, i代表索引下标,item是遍历到的元素(值)

案例:让li标签颜色越来越重


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>复制</title>
  <style>
    ul {
      list-style: none;
    }
    
    li {
      float: left;
      width: 200px;
      height: 200px;
      background: pink;
      text-align: center;
      line-height: 200px;
      margin: 0 20px 20px 0;
    }
  </style>
  
  <script src="jquery-2.2.4.js"></script>
  <script>
    $(function () {
      
//      for(var i = 0; i < $("li").length; i++) {
//        $("li").eq(i).css("opacity", (i+1)/10);
//      }
      //each方法
      $("li").each(function (index, element) {
        $(element).css("opacity", (index+1)/10);
      })
      
      
    });
  </script>
  
</head>

<body>
<ul id="ulList">
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
  <li>什么都看不见</li>
</ul>
</body>

</html>

手风琴效果(案例)

mouseenter(callback) 鼠标经过时触发

siblings() 方法返回被选元素的所有同级元素。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    ul {
      list-style: none;
      width: 1300px;
    }

    #box {
      width: 1200px;
      height: 400px;
      border: 2px solid red;
      margin: 100px auto;
    }

    #box li {
      width: 240px;
      height: 400px;
      /*border: 1px solid #000;*/
      float: left;
    }
  </style>
</head>

<body>
  <div id="box">
    <ul>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <script src="../jquery-2.2.4.js"></script>
  <script>
    // 1给li设置背景图片
    $('ul li').each((k, v) => {
      // console.log(v);
      // v 默认是dom节点对象
      $(v).css('background', 'url(../images/' + (k + 1) + '.jpg)')

    })

    // 2鼠标移入到那个li,其宽度为800,其他的为100
    $('ul li').mouseenter(function () {
      // console.log(this);
      $(this).stop().animate({ width: 800 }).siblings().stop().animate({ width: 100 })
    });

    //  3 鼠标移开,恢复到240
    $('ul').mouseleave(function () {
      // console.log(this);
      $('ul li').stop().animate({ width: 240 })
    });
  </script>
</body>

</html>

鼠标跟随

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    div.box {
      width: 600px;
      height: 200px;
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      border: 5px solid pink;
      margin: 50px auto;
      cursor: pointer;
    }

    div > p {
      width: 100px;
      height: 100px;
    }

    div > p > img {
      width: 100%;
      height: 100%;
      display: block;
    }

    .show {
      width: 288px;
      height: 180px;
      position: absolute;
      left: 0;
      top: 0;

      display: none;

      pointer-events: none;
    }

  </style>
</head>
<body>

  <div class="box">
    <p><img src="./imgs/1.png" alt=""></p>
    <p><img src="./imgs/2.png" alt=""></p>
    <p><img src="./imgs/3.png" alt=""></p>
  </div>

  <div class="show">
    <img src="./imgs/1.png" alt="">
  </div>

  <script src="./jquery/jquery.min.js"></script>
  <script>
    /*
      案例 - 鼠标跟随
    */

    // 1. 给每一个 p 绑定一个鼠标 移入 移出 移动 事件
    $('.box > p').on({
      mouseover () {
        // 修改 show 下面的 img 的 src 属性
        // 自己下面的 img 的 src 属性是啥, 就改成什么
        const url = $(this).find('img').prop('src')
        $('.show > img').prop('src', url)
        // 让 show 显示
        $('.show').stop().fadeIn(100)
      },
      mouseout () {
        // 让 show 隐藏
        $('.show').stop().fadeOut(100)
      },
      mousemove (e) {
        // 因为 offset() 方法, 可以把 show 盒子设置到距离文档流左上角的相对位置
        // 我要拿到光标距离文档流左上角的位置
        // offsetX 和 offsetY   相对于 事件目标 左上角的坐标位置
        // clientX 和 clientY   相对于 浏览器可视窗口 左上角的坐标位置
        // pageX 和 pageY       相对于 文档流 左上角的坐标位置
        $('.show').offset({ left: e.pageX, top: e.pageY })
      }
    })
  </script>
</body>
</html>

ajax

基本使用

在jQuery中发送一个Ajax请求常用的有以下方式:

①方式一 : $.ajax( object )

$.ajax基本语法:

$.ajax(对象)

jQuery 底层 AJAX 实现。此方法功能最强大,get和post请求都可以发送,回调函数也最多,如:发送之前、发送失败、发送成功、发送完毕的回调函数都可以设置。

参数说明:

object:是个json格式的对象,常用的键值有以下几种

键名说明
type请求的方式。常用的有get和post默认为get请求
url请求的地址。
data携带的请求参数,格式为请求字符串id=3&age=28或者json格式 {id:3,age:28}
async是否异步请求,默认为true异步,false同步
dataType指定服务器返回的数据类型,值有text、json、xml等如果是post请求,此参数application/x-www-form-urlencoded
cache是否允许缓存,默认为true缓存,false不缓存
success(重点)当Ajax状态码为4且http响应状态码为200时所触发的回调函数
beforeSend(重点)发送请求之前触发的回调函数,一般用做loading提示加载等效果。
complete当Ajax状态码(readyState)为4的时候所触发的回调函数
error发送失败的回调函数,如请求的文件不存在会触发

②方式二:简单易用的高级实现 (底层也是使用$.ajax实现的)

语法格式:

$.get(url, [data], [callback], [type])

$.post(url, [data], [callback], [type])

说明: . g e t ( ) 只能发送 g e t 请求, .get()只能发送get请求, .get()只能发送get请求,.post()只能发送post请求,且这两者都是异步请求。

参数说明:

url:请求的地址

data:请求的参数,请求字符串或者json格式

callback:请求成功的回调函数 相当于原生Ajax请求状态等于4

type:指定服务端返回的数据类型,有xml, json, text等

实际操作

原生js的写法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CvqXhStj-1663214062833)(/1565495007117.png)]

JQuery的实现

jquery的书写

<body>
    <input type="button" value="点击请求">
    <script>
     $('input').click(()=>{
         $.ajax({
             type:'get',
             url:'./ajax.php',
             data:'name=zs&age=18',
             dataType:'json',
             success:function(data){
                 console.log(data);
             }
         });
     });
    </script>
</body>

jQuery中的Ajax高级实现

1、ajax高级实现的基本语法

• $.get(url,[data],[callback],[type]) :发送Ajax中的get请求

• $.post(url,[data],[callback],[type]) :发送Ajax中的post请求

参数说明:

url :请求的url地址

[data] :可选参数,没有可以不写,代表要发送的数据,可以是字符串也可以是json对象

[callback] :可选参数,代表Ajax状态码为4且响应状态码为200时所触发的回调函数

[type] :可选参数,值可以是text,xml,json,默认为text

2、$.get应用

06-jq-get.html

<button id="btn">发送数据</button>
	<script>
		$(function(){
			$("#btn").click(function(){
				//发送ajax的get请求
				$.get("./06-jq-get.php","username=zhangsan",function(res){
					console.log(res);
				},"json");
				//使用ajax发送请求,等价于上面的这种写法
				$.ajax({
					"url":"./06-jq-get.php",
					"type":"get",
					"data":"username=zhangsan",
					"dataType":"json",
					"success":function(res){
						console.log(res);
					}
				})
			})
		})
	</script>
3、$.post应用

post方法和get方法语法完全一样。

  $('input').click(function(){
        $.post('./ajax.php','name=feng&age=18',function(res){
            console.log(res);
        });
       // 两种方式完全一样
        $.ajax({
            type:'post',
            url:'./ajax.php',
            data:'name=feng&age=18',
            dataType:'json', // 自动将json转化为对象
            success:(res)=>{
                console.log(res)
            }
        });
     });

表单数据的收集

定义和用法

serialize() 方法通过序列化表单值创建 URL 编码文本字符串。

您可以选择一个或多个表单元素(如输入和/或文本区),或表单元素本身

例1:收集表单中的数据

    <form action="">
        <input type="text" name="name" value="" id="">
        <input type="text" name="age" value="" id="">
    </form>
    <div>
    
    </div>
$("button").click(function(){
    $("div").text($("form").serialize());
})

Jquery中的跨域请求

js中跨域请求的原理:

script标签不受同源策略的限制.

请求步骤

1 给某个按钮,绑定点击点击事件,点击时发送请求
2 动态生成script标签,设置src的属性为后台文件的地址http://www.baidu.com?fn=callback
 callback是js中设置函数
3 追加到head中
4 定义一个 function callback(){}

服务器

1 接受fn
2 echo $fn.'()'  将函数名当做普通字符串输出

设置dataType为jsonp

$.ajax({
            url:"http://localhost:8888/gx", 
            dataType:"jsonp",
            jsonp: 'cb',
            jsonpCallback: 'aaa'
            success:function (data) {
                console.log(data)
            }
        })

弹幕效果

jquery中的键盘谈起事件

keyup(function(e){})

e.keyCode 获取点击的键盘码

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <style type="text/css">
    html, body {
      margin: 0px;
      padding: 0px;
      width: 100%;
      height: 100%;
      font-family: "微软雅黑";
      font-size: 62.5%;
    }
    
    .boxDom {
      width: 100%;
      height: 100%;
      position: relative;
      overflow: hidden;
    }
    
    .idDom {
      width: 100%;
      height: 100px;
      background: #666;
      position: fixed;
      bottom: 0px;
    }
    .content {
      display: inline-block;
      width: 430px;
      height: 40px;
      position: absolute;
      left: 0px;
      right: 0px;
      top: 0px;
      bottom: 0px;
      margin: auto;
    }
    
    .title {
      display: inline;
      font-size: 4em;
      vertical-align: bottom;
      color: #fff;
    }
    
    .text {
      border: none;
      width: 300px;
      height: 30px;
      border-radius: 5px;
      font-size: 2.4em;
    }
    
    .btn {
      width: 60px;
      height: 30px;
      background: #f90000;
      border: none;
      color: #fff;
      font-size: 2.4em;
    }
    
    span {
      width: 300px;
      height: 40px;
      position: absolute;
      overflow: hidden;
      color: #000;
      font-size: 4em;
      line-height: 1.5em;
      cursor: pointer;
      white-space: nowrap;
    }
  
  </style>
</head>

<body>

<div class="boxDom" id="boxDom">
  <div class="idDom" id="idDom">
    <div class="content">
      <p class="title">吐槽:</p>
      <input type="text" class="text" id="text"/>
      <button type="button" class="btn" id="btn">发射</button>
    </div>
  </div>
</div>
</body>

<script src="../jquery-2.2.4.js"></script>
<script>
  $(function () {
    //注册事件
    var colors = ["red", "green", "hotpink", "pink", "cyan", "yellowgreen", "purple", "deepskyblue"];
    $("#btn").click(function () {
      var randomColor = parseInt(Math.random() * colors.length);
      var randomY = parseInt(Math.random() * 400);
      
      $("<span></span>")//创建span
        .text($("#text").val())//设置内容
        .css("color", colors[randomColor])//设置字体颜色
        .css("left", "1400px")//设置left值
        .css("top", randomY)//设置top值
        .animate({left: -500}, 10000, "linear", function () {
          //到了终点,需要删除
          $(this).remove();
        })//添加动画
        .appendTo("#boxDom");
      
      
      $("#text").val("");
    });
    
    
    $("#text").keyup(function (e) {
      if (e.keyCode == 13) {
        $("#btn").click();
      }
    });
    
  });

</script>
</html>
//注册事件
var colors = ["red", "green", "hotpink", "pink", "cyan", "yellowgreen", "purple", "deepskyblue"];
$("#btn").click(function () {
  var randomColor = parseInt(Math.random() * colors.length);
  var randomY = parseInt(Math.random() * 400);
  
  $("<span></span>")//创建span
    .text($("#text").val())//设置内容
    .css("color", colors[randomColor])//设置字体颜色
    .css("left", "1400px")//设置left值
    .css("top", randomY)//设置top值
    .animate({left: -500}, 10000, "linear", function () {
      //到了终点,需要删除
      $(this).remove();
    })//添加动画
    .appendTo("#boxDom");
  
  
  $("#text").val("");
});


$("#text").keyup(function (e) {
  if (e.keyCode == 13) {
    $("#btn").click();
  }
});

});

```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值