前端 -- jQuery

一、jQuery文档(非常详细!)

在这里插入图片描述
在这里插入图片描述

二、选择器、过滤器、回调函数

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<!-- 要使用jquery,必须先引用jQuery包,这个引用必须在所有的js代码之前 -->
		<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
	</head>
	<body>
		<h1 id="hhh">欢迎你!</h1>
		<ul>
			<li>苹果</li>
			<li>橘子</li>
			<li>西瓜</li>
		</ul>

		<script type="application/javascript">
			console.log($("#hhh"));	// id选择器
			console.log($("ul>li"));	// 子选择器
			console.log($("li:first"));	// 基本选择器
			console.log($("ul>li").first());	// 过滤器
		
			// 遍历
			// 获取元素
			var $lis = $("ul>li");	// jquery对象
			var lis = document.getElementsByTagName("li");	// js对象
			// 操作元素
			$lis.each(function(index, element){
				// 回调函数,最后执行w
				console.log(index);
				console.log(element.innerHTML);	// each里将每一个元素作为js对象
			})
		</script>
	</body>
</html>

效果:
在这里插入图片描述
在这里插入图片描述

二、事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
	</head>
	<body>
		<form action="#">
			姓名:<input type="text" name="userName" /><br />
			密码:<input type="password" name="userPwd" /><br />
			<input type="submit" value="登录" />
		</form>
		<hr />
		<ul>
			<li>苹果</li>
			<li>橘子</li>
			<li>西瓜</li>
		</ul>
		<input type="text" id="ulli" /><input type="button" id="btn" value="添加" >
		
		<script type="text/javascript">
			$(":input:first").blur(function(){
				var val = $(this).val();	//注意,val()函数,当括号内没有值是返回,有值是赋值
				console.log(val);
			});
			
			$("form:first").submit(function(){
				$("input").each(function(index,element){
					if(element.value=="" || element.value==null){
						alert("用户名和密码不能为空!")
						return false;
					}
				})
				return true;
			});
			
			// live(type, fn):给所有匹配的元素附加一个事件处理函数,即使这个元素是以后再添加进来的也有效。
			// JS做不到选中非原始代码给来的元素
			$("li").live("click",function(){
				alert($(this).html());
			})
			
			// text():获取元素的内容和子元素的内容
			// html():获取元素的html文档所有内容
			// val():获取表单元素的value值
			$(":button").first().click(function(){
				$("ul:first").append($("<li>").html($("#ulli").val()));
			})
		</script>
	</body>
</html>

效果:
在这里插入图片描述

三、动画

3.1 普通动画、自定义动画

!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
		<style type="text/css" >
			#div1{
				top: 90px;
				width:200px;
				height:200px;
				background-color: powderblue;
				position:absolute;
				left:0;
				right:0;
			}
		</style>
	</head>
	<body>
		<div id="div1"></div>
		<input type="button" id="btn1" value="滑动显示" />
		<input type="button" id="btn2" value="隐藏" />
		<input type="button" id="btn3" value="显示或隐藏" />
		<input type="button" id="btn4" value="自定义动画" />
		<script type="text/javascript">
			$("#btn1").click(function(){
				$("#div1").slideDown("slow");
			});
			$("#btn2").click(function(){
				$("#div1").hide();
			});
			$("#btn3").click(function(){
				$("#div1").toggle();
			});
			$("#btn4").click(function(){
				$("#div1").animate({
					width:"100px",
					height:"50px",
					left:"200px",
					top:"35px"
				},5000);
			});
		</script>
	</body>
</html>

效果:
在这里插入图片描述

3.2 应用(图片轮播)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>轮播效果</title>
		<script src="js/jquery-1.8.3.min.js"></script>
		<style>
			*{
				margin: 0 auto;
				padding: 0;
			}
			#father{
				width: 320px;
				height: 180px;
				overflow: hidden;
				position: relative;
			}
			#ul1{
				width: 1280px;
				height: 180px;
				position: absolute;
				top: 0;
				left: 0;
			}
			#ul1>li{
				width: 320px;
				height: 180px;
				float: left;
			}
			#ul2{
				width: 108px;
				height: 36px;
				position: absolute;
				bottom: 5px;
				right: 5px;
			}
			#ul2>li{
				width: 26px;
				height: 26px;
				margin: 5px;
				float: left;
				line-height: 26px;
				font-size: 18px;
				color: white;
				text-align: center;
				cursor: pointer;
				border-radius: 50%;
				background-color: rgba(0,0,0,0.6);
			}
			#son1{
				width: 26px;
				height: 26px;
				position: absolute;
				top: 77px;
				left: 0;
				background-color: rgba(0,0,0,0.5);
				line-height: 26px;
				font-size: 15px;
				color: white;
				text-align: center;
				cursor: pointer;
			}
			#son2{
				cursor: pointer;
				width: 26px;
				height: 26px;
				position: absolute;
				top: 77px;
				right: 0;
				background-color: rgba(0,0,0,0.5);
				line-height: 26px;
				font-size: 15px;
				color: white;
				text-align: center;
			}
			li{
				list-style-type: none;
			}
		</style>
	</head>
	<body>
		<div id="father">
			<ul id="ul1">
				<!--最后多出第一张图片-->
				<li><img src="imgs/1.jpg" width="320" height="180" /></li>
				<li><img src="imgs/2.jpg" width="320" height="180" /></li>
				<li><img src="imgs/3.jpg" width="320" height="180" /></li>
				<li><img src="imgs/1.jpg" width="320" height="180" /></li>
			</ul>
			<ul id="ul2">
				<li>1</li>
				<li>2</li>
				<li>3</li>
			</ul>
			<div id="son1">&lt;</div>
			<div id="son2">&gt;</div>
		</div>
		<script>
			/*初始绑定*/
			var isAnimate = false;  //动画状态定义
			var playTime = null;  //跳转动画计时器
			var points = [0,-320,-640,-960];  //记录火车定位
			
			father.onmouseover = stop;  //鼠标移入停止自动播放
            father.onmouseout = play;  //鼠标移除继续播放
			
            $("#ul2>li").each(function(index,ele){  //每一个数字按钮绑定单击事件
            	$(this).click(function(){
            		myAnimate(points[index]);
            	});
            });
            $("#son1").click(function(){  //前一张按钮绑定单击之间
            	if(!isAnimate){  //判断是否在动画中 意义在于防止连续点击
            		isAnimate=true;  //“上锁”
	            	var leftPont = parseInt($("#ul1").css("left"));  //获取当前位置
	            	if(leftPont==0){  //如果是第一张图片
	           			$("#ul1").css("left","-960px");  //置为最后一张
	           		}
	            	$("#ul1").animate({'left':parseInt($("#ul1").css("left"))+320+"px"},1000,function(){
	            		isAnimate=false;  //在回调函数中“取锁”  回调函数:当动画完成后执行!
	            	});
            	}
            	
            });
            $("#son2").click(function(){  //下一张按钮绑定事件
            	myAnimate();
            });
            play();
            
            /*定义函数*/
           	function myAnimate(toPoint){  //图片过渡动画函数
           		if(!isAnimate){  //判断是否在动画中
           			isAnimate=true;  //“上锁”
           			if((parseInt($("#ul1").css("left")))-320<-960){
	           			$("#ul1").css("left","0");
	           		}
	           		if(toPoint==null){
	           			toPoint=(parseInt($("#ul1").css("left")))-320;
	           		}
	           		$("#ul1").animate({'left':toPoint+"px"},1000,function(){
	           			isAnimate=false;  //在回调函数中“取锁”
	           		});
	           		
           		}
           		
           	}
			function play(){  //开始播放动画函数
				playTime=setInterval(function(){
					myAnimate();
				},2000);
			}
			function stop(){  //停止动画函数
				if(playTime!=null){
					clearInterval(playTime);
				}
			}
		</script>
	</body>
</html>

效果:
在这里插入图片描述

四、JQuery的Ajax技术

4.1 使用

JQuery 是一个优秀的 JS 框架,自然对 JS 原生的 Ajax 进行了封装,封装后的 Ajax 的操作方法更简洁,功能更强大,但开发中经常使用的有三种:

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

这两种封装中的参数:

  • url:代表请求的服务器端地址
  • data:代表请求服务器端的数据(可以是 key = value 形式也可以是JSON格式)
  • callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
  • type:表示服务器端返回的数据类型(JQuery 会根据指定的类型自动类型转换),常用的返回类型有:text、json、html 等
  1. $.ajax( { option1:value1,option2:value2… } ); // 最底层的方法

这种封装中常用的 option 有如下:

  • async:是否异步,默认是 true 代表异步
  • data:发送到服务器的参数,建议使用 JSON 格式
  • dataType:服务器端返回的数据类型,常用 text 和 JSON
  • success:成功响应执行的函数,对应的类型是 function 类型
  • type:请求方式,POST/GET
  • url:请求服务器端地址
  • error:失败的回调函数,对应的类型是function类型

4.2 应用:当页面加载完成后,将ct表(商品类型表)填充进select标签中

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery#Ajax</title>
<script src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
当页面加载完成后,将ct表(商品类型表)填充进select标签中
<select></select>
<script type="text/javascript">
	$.post("/day_0924_web9/loadCommoditytypeListServlet", function(data){
		//console.log(data);
		for(var i=0;i<data.length;i++){
			$("select:first").attr("name","ct_id").append($("<option>").attr("value",data[i].ct_id).html(data[i].ct_name));
		}
	}, "json")		// $.post(发送请求地址, 发送成功时回调函数, 返回内容格式)
</script>
</body>
</html>

LoadCommoditytypeListServlet.java

package com.ishopn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.ishopn.controller.CommoditytypeController;
import com.ishopn.model.Commoditytype;

public class LoadCommoditytypeListServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		List<Commoditytype> ctList = new CommoditytypeController().getCommoditytypeList();
		PrintWriter writer = resp.getWriter();
		writer.write(JSON.toJSONString(ctList));
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}

效果:
在这里插入图片描述

4.3 应用:模糊查询

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>模糊查询</title>
<script src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
模糊查询:
<input type="text" id="wd" />
<ul></ul>
<script type="text/javascript">
	$("#wd").keyup(function(){
		$("ul:first").html("");
		var wd = $(this).val();
		if(wd!=null && wd.length>0){
			$.post("/day_0924_web9/getCommodityLikeName",{'wd':wd},function(data){
				if(data.length>0){
					for(var i=0;i<data.length;i++){
						$("ul:first").append($("<li>").html(data[i].c_name+"|"+data[i].ct.ct_name));
					}
				}else{
					$("ul:first").html("");
				}
			},'json')	// data:待发送 Key/value 参数
		}
	})
</script>
</body>
</html>

GetCommodityLikeName.java

package com.ishopn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.ishopn.controller.CommodityController;
import com.ishopn.model.Commodity;

public class GetCommodityLikeName extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		String wd = req.getParameter("wd");
		List<Commodity> cList = new CommodityController().getCommodityListLikeName(wd);
		PrintWriter writer = resp.getWriter();
		writer.write(JSON.toJSONString(cList));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

效果:
在这里插入图片描述

五、表单序列化

如果想让表单通过 Ajax 异步提交,那么首先我们要通过 JS 获取到每个表单中输入的值,如果表单项比较多的话,想必又是一件很麻烦,很痛苦的事情,那么我们可以通过 JQuery 的表单序列化的操作将表单的数据拼接成提交的参数格式 即:name=value&name=value&name=value 或者 json 格式对象。
例如:表单如下
在这里插入图片描述
使用 serialize() 方法:

<script type="text/javascript" src="./jquery-1.8.3.min.js"</script>
<script type="text/iavascript">
	$(function(){
		fn = function(){
			var formData = $(document.getElementById("myform")).serialize();
			alert(formData);
		};
	});
</script>

效果:
在这里插入图片描述

推荐一篇更详细的博客:https://blog.csdn.net/qq_39949109/article/details/80209397

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值