例1、javascript典型例子。Javascript解析html和解析xml文件时一样的
第一步、cities.xml
<?xml version="1.0" encoding="UTF-8"?>
<china>
<province name="吉林省">
<city>长春</city>
<city>吉林市</city>
<city>四平</city>
<city>松原</city>
<city>通化</city>
</province>
<province name="辽宁省">
<city>沈阳</city>
<city>大连</city>
<city>鞍山</city>
<city>抚顺</city>
<city>铁岭</city>
</province>
<province name="山东省">
<city>济南</city>
<city>青岛</city>
<city>威海</city>
<city>烟台</city>
<city>潍坊</city>
</province>
</china>
第二步、city.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>city.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<select id="province" name="province">
<option value="">请选择...</option>
<option value="吉林省">吉林省</option>
<option value="辽宁省">辽宁省</option>
<option value="山东省">山东省</option>
</select>
<select id="city" name="city">
<option value="">请选择...</option>
</select>
</body>
<script type="text/javascript"> window.onload=function(){ var provinceElement = document.getElementById("province"); //1.注册<select id="province" name="province">onchange事件 provinceElement.onchange=function(){ //alert("xx"); /**************************************************************/ //清空下拉选的值 var cityElement=document.getElementById("city"); var cityOptionElements = cityElement.getElementsByTagName("option"); var len=cityOptionElements.length; //javascript 是一个动态的数组,所以删除的时候从后往前删,注意for循环里面的内容 for(var i=len-1;i>0;i--){ cityElement.removeChild(cityOptionElements[i]); } /**************************************************************/ //声明 var provinceElement=null; //2.获取第一个下拉选的值 var pvalue=this.value; //alert(pvalue); //3.加载xml文件 var xmlDoc= parseXML("cities.xml"); //4.获取xmlprovince标签 var provinceXmlElements = xmlDoc.getElementsByTagName("province"); //alert(provinceXmlElements.length); //5.遍历xml文件中所有province标签 if(provinceXmlElements!=null){ for(var i=0;i<provinceXmlElements.length;i++){ //6.获取province标签 var provinceXmlElement=provinceXmlElements[i]; //7.获取province标签的name属性 var xmlProvinceNameValue=provinceXmlElement.getAttribute("name"); //8.下拉选变化的值与name属性做比对、 //9.如相等,则找到了 if(pvalue==xmlProvinceNameValue){ //10.保存province标签的到一个变量中 provinceElement=provinceXmlElement; //10.中止循环 break; } } } if(provinceElement!=null){ var xmlCityElements=provinceElement.getElementsByTagName("city"); for(var i=0;i<xmlCityElements.length;i++){ var xmlCityElement=xmlCityElements[i]; //alert(xmlCityElement.firstChild.nodeValue); var cityValue=xmlCityElement.firstChild.nodeValue; //<option value="">请选择...</option> var optionElement=document.createElement("option"); optionElement.setAttribute("value",cityValue); var optionTextElement=document.createTextNode(cityValue); optionElement.appendChild(optionTextElement); cityElement=document.getElementById("city"); cityElement.appendChild(optionElement); } } } } /* * 加载xml文件的函数 */ function parseXML(filename){ var xmlDoc; try //Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); } catch(e) { try //Firefox, Mozilla, Opera, etc. { xmlDoc=document.implementation.createDocument("","",null); } catch(e) { //alert(e.message); return; } } xmlDoc.async=false;//关闭异步加载 xmlDoc.load(filename);//解析器加载filename的xml文件 return xmlDoc; } </script>
</html>
例2、innerHtml
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>innerHtml.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="city"></div>
</body>
<script language="JavaScript"> //在div层中插入<h1>今天</h1> var cityElement=document.getElementById("city"); cityElement.innerHTML="<h1>今天</h1>"; </script>
</html>
例3、弹出对话框选择。
showDialog_1.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>showDialog_1.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<script language="JavaScript"> function viewData(cid,cname){ /* * 客户编号:<input type="text" name="cid" value="" id="cid"> 客户名称:<input type="text" name="cname" value="" id="cname"> */ //获取showDialog_2.html的内容,dialogArguments保存showDialog_2.html页面的内容 var s2data=window.dialogArguments; s2data.setDocumentValue(cid,cname); window.close(); } </script>
<body>
<table border="1">
<tr>
<td>操作</td>
<td>客户id</td>
<td>客户名称</td>
</tr>
<tr>
<td><input type="button" value="选择" id="ss" onclick="viewData('001','深圳华为');"></td>
<td>001</td>
<td>深圳华为</td>
</tr>
<tr>
<td><input type="button" value="选择" onclick="viewData('002','北京用友');"></td>
<td>002</td>
<td>北京用友</td>
</tr>
</table>
</body>
</html>
showDialog_2.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>showDialog_2.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<script language="JavaScript"> function openWin(){ /* * 第一个参数:必选项,字符串String,指定要载入和显示的URL * 第二个参数:可选项。指定供显示文档时使用的变量。利用这个参数 可以传递任何类型的值,包括包含多个值得的数组。对话框可以 通过调用程序从 window 对象的 dialogArguments 属性提取这些值。 * 第三个参数:可选项。字符串(String)。指定对话框的窗口装饰。使用下面的值。多个之间用分号隔开。 */ //1.非模态对话框 window.showModelessDialog("showDialog_1.html",window,"status:no;dialogHeight:210px;dialogWidth:360px;help:no"); //2.模态对话框 //window.showModelessDialog("showDialog_1.html",window,"status:no;dialogHeight:210px;dialogWidth:360px;help:no"); } function setDocumentValue(cid,cname){ document.getElementById("cid").value=cid; document.getElementById("cname").value=cname; } </script>
<body>
<form name="form1" action="test.html" method="post">
客户编号:<input type="text" name="cid" value="" id="cid">
客户名称:<input type="text" name="cname" value="" id="cname">
<input type="button" name="ok" value="请选择客户" onclick="openWin();">
</form>
</body>
</html>
例4、实现例3同样的功能,但是采用不同的方法
A1.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>showDialog_2.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<script language="JavaScript"> //在新窗口显示a2.html /* * _blank :在新窗口中打开sUrl */ function openWin(){ window.open("a2.html","_blank",'height=200,width=400,status=no,toolbar=no,menubar=no,location=no'); } </script>
<body>
<form name="form1" action="test.html" method="post">
客户编号:<input type="text" name="cid" value="" id="cid">
客户名称:<input type="text" name="cname" value="" id="cname">
<input type="button" name="ok" value="请选择客户" onclick="openWin();">
</form>
</body>
</html>
A2.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>showDialog_1.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<script language="JavaScript"> function viewData(cid,cname){ //opener表示父窗口的值 window.opener.document.getElementById("cid").value=cid; window.opener.document.getElementById("cname").value=cname; //不再使用父窗口的内容 window.opener=null; window.close(); } </script>
<body>
<table border="1">
<tr>
<td>操作</td>
<td>客户id</td>
<td>客户名称</td>
</tr>
<tr>
<td><input type="button" value="选择" id="ss" onclick="viewData('001','深圳华为');"></td>
<td>001</td>
<td>深圳华为</td>
</tr>
<tr>
<td><input type="button" value="选择" onclick="viewData('002','北京用友');"></td>
<td>002</td>
<td>北京用友</td>
</tr>
</table>
</body>
</html>
例5、ajax的第一个应用实例
第一步、TestServlet.java
package cn.itcast.web;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("request.getMethod"+request.getMethod());
System.out.println("request.getRequestUri"+request.getRequestURI());
System.out.println("********doGet()**********");
System.out.println(request.getParameter("b"));
PrintWriter out=response.getWriter();
//服务器返回到客户端,这是一个文本
out.println("Connection server ******");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第二步、test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test.jsp</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- 引入js -->
<script type="text/javascript" src="${pageContext.request.contextPath}/testget/test.js"> </script>
</head>
<body>
<input type="button" name="ok" id="ok" value="测试和服务器的连接"><br>
</body>
</html>
第三步、test.js
function ajaxFunction(){
var xmlHttp;
try{//火狐
xmlHttp=new XMLHttpRequest();
}catch(e){
try {//IE
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
/*点击ok按钮执行Servlet的doGet方法 * 1.初始化XMLHttpRequest对象(支持异步请求) * 2.建立与服务器的连接 * 3.发送请求 * 4.处理服务器端发回的请求(随时发回的) */
/* * 创建XMLHttpRequest对象的函数 */
var xmlHttp=null;
window.onload=function(){
document.getElementById("ok").onclick=function(){
//1.初始化XMLHttpRequest对象
xmlHttp=ajaxFunction();
/****************************************************************************/
//2.定义事件处理函数,等号后面如果加函数名,函数名不需要加括号
//事件处理函数,服务器的状态每次发生改变(0,1,2,3,4)都会调用该函数
xmlHttp.onreadystatechange=function(){
alert(xmlHttp.readyState+" "+xmlHttp.status);//1,1,2,3,4
//xmlHttp.readyState==4:响应发送完毕
if(xmlHttp.readyState==4){
if(xmlHttp.status==200||xmlHttp.status==304){
//如果服务器返回的是文本类型,用xmlHttp.responseText来接收
alert(xmlHttp.responseText);
}
}
}
/****************************************************************************/
/*3.建立到服务器的连接 * * 第一个参数:请求方法get/post * * 第二个参数:请求路径url,(加上时间戳可以告诉浏览器不要缓存响应,后面可 * 以加上传送的数据,在servlet中用request.getParameter来取) * * 第三个参数:表示请求是否异步传输 * 注意:第二个参数的相对路径 * */
xmlHttp.open("get","../servlet/TestServlet?timeStamp="+new Date().getTime()+"&b=123",true);
/*4.发送请求 * 若为get请求,将不会发送任何数据,为null */
//alert("xx");
xmlHttp.send(null);
}
}
例6、POST方式提交数据
第一步、TestServlet.java
package cn.itcast.web;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("request.getMethod"+request.getMethod());
System.out.println("request.getRequestUri"+request.getRequestURI());
System.out.println("********doGet()**********");
System.out.println(request.getParameter("a"));
System.out.println(request.getParameter("b"));
System.out.println(request.getParameter("c"));
PrintWriter out=response.getWriter();
//服务器返回到客户端,这是一个文本
out.println("Connection post server ******");
}
}
第二步、test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test.jsp</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- 引入js -->
<script type="text/javascript" src="${pageContext.request.contextPath}/testpost/test.js"> </script>
</head>
<body>
<input type="button" name="ok" id="ok" value="测试和服务器的连接"><br>
</body>
</html>
第三步、test.js
function ajaxFunction(){
var xmlHttp;
try{//火狐
xmlHttp=new XMLHttpRequest();
}catch(e){
try {//IE
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
var xmlHttp=null;
window.onload=function(){
document.getElementById("ok").onclick=function(){
xmlHttp=ajaxFunction();
/****************************************************************************/
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200||xmlHttp.status==304){
alert(xmlHttp.responseText);
}
}
}
/****************************************************************************/
xmlHttp.open("post","./servlet/TestServlet?timeStamp="+new Date().getTime()+"&a=123",true);
/* 1.如果用POST请求想服务器发送数据,需要将"Content-Type"的首部设置为application/x-www-form-urlencoded他会告诉服务器正在发送数据,并且数据已经符合URL编码了 * 2.该方法必须放在open方法的后面 */
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//若选用的是post方法,可以传递数据
xmlHttp.send("b=fandong12388&c=fandong8299799");
}
}
第四步、运行结果
request.getMethodPOST
request.getRequestUri/day24ajax01/servlet/TestServlet
***doGet()*****
123
fandong12388
fandong8299799
例7、网站注册页面。
第一步、RegisterServlet.java
package cn.itcast.web;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
//获取用户名 连接数据库进行处理
String username = request.getParameter("username");
if("sa".equals(username)){
out.println("用户名已存在");
}else{
out.println("用户名可以注册");
}
}
}
第二步、register.jsp
……
<script type="text/javascript" src="${pageContext.request.contextPath}/register/test.js"></script>
</head>
<body>
<form action="" method="post">
<h2>请填写用户注册信息</h2><br>
<table border="1">
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username" value="" id="username"/>
<div id="divcheck"></div>
<input type="button" name="checkusername" value="查询" id="checkusername"/>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="password" value="" id="password"/>
</td>
……
第三步、test.js
function ajaxFunction(){
var xmlHttp;
try{//火狐
xmlHttp=new XMLHttpRequest();
}catch(e){
try {//IE
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
var xmlHttp=null;
window.onload=function(){
document.getElementById("checkusername").onclick=function(){
//1.获取页面<input type="text" name="username" value="" id="username"/>的值
var username=document.getElementById("username").value;
xmlHttp=ajaxFunction();
/****************************************************************************/
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200||xmlHttp.status==304){
var str = xmlHttp.responseText;
//<div id="divcheck"></div>
//alert(str);
document.getElementById("divcheck").innerHTML=str;
}
}
}
/****************************************************************************/
xmlHttp.open("post","../servlet/RegisterServlet?timeStamp="+new Date().getTime(),true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("username="+username);
}
}
例8、ajax处理xml文件
第一步、
第二步、XmlServlet.java
package cn.itcast.web;
public class XmlServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
//设置返回的mime类型是text/xml
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
StringBuffer buf=new StringBuffer();
buf.append("<china>");
buf.append("<province name='吉林省'>");
buf.append("<city>长春</city><city>吉林市</city><city>四平</city><city>通化</city>");
buf.append("</province>");
buf.append("<province name='山东省'>");
buf.append("<city>济南</city><city>枣庄</city><city>济宁</city><city>临沂</city>");
buf.append("</province>");
buf.append("<province name='四川省'>");
buf.append("<city>成都</city><city>绵阳</city><city>德阳</city><city>巴中</city>");
buf.append("</province>");
buf.append("</china>");
out.println(buf.toString());
}
}
第三步、xmlfile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>级联菜单</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/xmlfile/xmlFile.js"></script>
</head>
<body>
<select id="province" name="province">
<option value="">请选择...</option>
</select>
<select id="city" name="city">
<option value="">请选择...</option>
</select>
</body>
</html>
第四步、xmlFile.js
/****************************************************************************/
function ajaxFunction(){
var xmlHttp;
try{//火狐
xmlHttp=new XMLHttpRequest();
}catch(e){
try {//IE
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
/****************************************************************************/
var xmlHttp=null;
window.onload=function(){
//1.创建XMLHttpRequest
xmlHttp=ajaxFunction();
//2.指定事件处理程序
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200 || xmlHttp.status == 304) {
//服务器返回的是一个xml文件
var xmlDoc=xmlHttp.responseXML;
var provinceElements = xmlDoc.getElementsByTagName("province");
//获取<province name='吉林省'>
for (var i = 0; i < provinceElements.length; i++) {
var provinceName = provinceElements[i].getAttribute("name");
var optionElement = document.createElement("option");
optionElement.setAttribute("value", provinceName);
var textElement = document.createTextNode(provinceName);
optionElement.appendChild(textElement);
var provinceSelectElement = document.getElementById("province");
provinceSelectElement.appendChild(optionElement);
}
var provinceElement=document.getElementById("province");
provinceElement.onchange = function(){
/**************************************************************/
var cityElement = document.getElementById("city");
var cityOptionElements = cityElement.getElementsByTagName("option");
var len = cityOptionElements.length;
for (var i = len - 1; i > 0; i--) {
cityElement.removeChild(cityOptionElements[i]);
}
/**************************************************************/
var provinceElement = null;
var pvalue = this.value;
var provinceXmlElements = xmlDoc.getElementsByTagName("province");
if (provinceXmlElements != null) {
for (var i = 0; i < provinceXmlElements.length; i++) {
var provinceXmlElement = provinceXmlElements[i];
var xmlProvinceNameValue = provinceXmlElement.getAttribute("name");
if (pvalue == xmlProvinceNameValue) {
provinceElement = provinceXmlElement;
break;
}
}
}
if (provinceElement != null) {
var xmlCityElements = provinceElement.getElementsByTagName("city");
for (var i = 0; i < xmlCityElements.length; i++) {
var xmlCityElement = xmlCityElements[i];
var cityValue = xmlCityElement.firstChild.nodeValue;
var optionElement = document.createElement("option");
optionElement.setAttribute("value", cityValue);
var optionTextElement = document.createTextNode(cityValue);
optionElement.appendChild(optionTextElement);
cityElement = document.getElementById("city");
cityElement.appendChild(optionElement);
}
}
}
}
}
}
//3.建立连接
/****************************************************************************/
xmlHttp.open("post","../servlet/XmlServlet?timeStamp="+new Date().getTime(),true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4.发送请求
xmlHttp.send(null);
}
JSON
例1、javascript对象的创建和访问
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>json.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
<script language="JavaScript"> /*java中对象的创建和访问: * class Person(){ * public namae; * public tel; * } * Person person=new Person(); * person.name; * person.tel; * */ //javascript中对象的创建与访问 var person={"name":"zhang","tel":"1234"}; alert(person.name); </script>
</html>
例2、创建多个对象
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>json.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
<script language="JavaScript"> /* * 表示多个人的信息 */ var person= [ {"name":"zhang","tel":"1234"}, {"name":"li","tel":"5678"}, {"name":"fandong","tel":"8901"} ] alert(person[0].name); alert(person[1].name); alert(person[2].name); </script>
</html>
例3、多个对象2
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>json.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
<script language="JavaScript"> /* * 表示多个人的信息 * 名称:值="params":数组 */ var person={"params":[ {"name":"zhang","tel":"1234"}, {"name":"li","tel":"5678"}, {"name":"fandong","tel":"8901"} ]}; alert(person.params[0].name);//zhang </script>
</html>
例4、多个对象之3
……
<script language="JavaScript">
/*
* 表示多个人的信息
* 名称1:值1",名称2:值2,名称3:值3,名称4:值4 */ var person={"params1":[ {"name":"zhang1","tel":"1234"}, {"name":"li1","tel":"5678"}, {"name":"fandong1","tel":"8901"} ], "params2":[ {"name":"zhang2","tel":"1234"}, {"name":"li2","tel":"5678"}, {"name":"fandong2","tel":"8901"} ], "params3":[ {"name":"zhang3","tel":"1234"}, {"name":"li3","tel":"5678"}, {"name":"fandong3","tel":"8901"} ], "params4":[ {"name":"zhang4","tel":"1234"}, {"name":"li4","tel":"5678"}, {"name":"fandong4","tel":"8901"} ]}; alert(person.params1[0].name); </script> ……
例5、javascript多个对象的创建和访问—-JSON对象
,……
<script language="JavaScript"> /* * 表示多个人的信息 */ var person={ "username":"zhang", "age":"20", "info":{"tel":"0102434","celltel":"12345"}, "address":[ {"address":"海淀","pcode":"6336623"}, {"address":"通州","pcode":"6336645"} ] }; alert(person.info.celltel); alert(person.address[1].pcode); </script>
</html>
例6、JSON对象与servlet之间的交互实例
第一步、
第二步、
package cn.itcast.web;
public class JsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
String jsonStr="{\"name\":\"zhangsan\",\"tel\":\"123456\"}";
//上面一行等同于String jsonStr="{name:'zhangsan',tel:'789'}";
out.println(jsonStr);
}
}
第三步、jsonServlet.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jsonServlet.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
<script language="JavaScript"> function ajaxFunction(){ var xmlHttp; try{//火狐浏览器 xmlHttp=new XMLHttpRequest(); }catch(e){ try {//IE xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return xmlHttp; } window.onload=function(){ //1.创建XMLHttpRequest xmlHttp=ajaxFunction(); //2.指定时间处理程序 xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200 || xmlHttp.status == 304) { var jsonStr=xmlHttp.responseText; //alert(jsonStr); //利用eval函数,把服务器传递过来的String转化为javascript可以识别的格式 var jsonObj=eval("("+jsonStr+")"); alert(jsonObj); var nameValue=jsonObj.name; alert(nameValue); } } } //3.建立连接 /****************************************************************************/ xmlHttp.open("post","../servlet/JsonServlet?timeStamp="+new Date().getTime(),true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //4.发送请求 xmlHttp.send(null); } </script>
</html>
第四步、在IE中键入http://localhost:8080/day24ajax01/json/jsonServlet.html 可以看到效果
注意:在定义json对象的时候,冒号后面的值需要加上引号,前面的可以不加!!!
例7、json表达式创建javascript对象之综合案例分析。
第一步、Province.java
package cn.itcast.bean;
public class Province {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Province(String id, String name) {
this.id = id;
this.name = name;
}
}
第二步、JsonServlet02.java
package cn.itcast.web;
public class JsonServlet02 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
/* [ * {id:1,name="吉林省"}, * {id:2,name="山东省"}, * {id:3,name="辽宁省"} * ] * */
Province p1=new Province("1", "吉林省");
Province p2=new Province("2", "山东省");
Province p3=new Province("3", "辽宁省");
List<Province> list=new ArrayList<Province>();
list.add(p1);
list.add(p2);
list.add(p3);
StringBuffer sb=new StringBuffer("[");
for(int i=0;i<list.size();i++){
Province p=(Province)list.get(i);
sb.append("{id:"+p.getId()+",name:'"+p.getName()+"'},");
}
sb.deleteCharAt(sb.length()-1);
sb.append("]");
System.out.println(sb.toString());//[{id:1,name:'吉林省'},{id:2,name:'山东省'},{id:3,name:'辽宁省'}]
out.print(sb.toString());
}
}
第三步、jsonServlet02.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jsonServlet.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
<script language="JavaScript"> function ajaxFunction(){ var xmlHttp; try{//火狐浏览器 xmlHttp=new XMLHttpRequest(); }catch(e){ try {//IE xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return xmlHttp; } window.onload=function(){ //1.创建XMLHttpRequest xmlHttp=ajaxFunction(); //2.指定时间处理程序 xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200 || xmlHttp.status == 304) { var jsonStr=xmlHttp.responseText; //利用eval函数,把服务器传递过来的String转化为javascript可以识别的格式 alert(jsonStr); var jsonObj=eval("("+jsonStr+")"); alert(jsonObj); var nameValue=jsonObj[0].name; alert(nameValue); } } } //3.建立连接 /****************************************************************************/ xmlHttp.open("post","../servlet/JsonServlet02?timeStamp="+new Date().getTime(),true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //4.发送请求 xmlHttp.send(null); } </script>
</html>
第四步、在IE中访问:http://localhost:8080/day24ajax01/json/jsonServlet02.html
例8、创建json表达式(javascript对象)的几种方法:
第一步、导包
第二步、Province.java
package cn.itcast.bean;
public class Province {
private String id;
private String name;
private String description="fandong";
public Province() {
}
public Province(String id, String name) {
this.id = id;
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第三步、Test.java
package cn.itcast.web;
public class Test {
public static void main(String[] args) {
Province p1=new Province("1", "吉林省");
Province p2=new Province("2", "山东省");
Province p3=new Province("3", "辽宁省");
List<Province> list=new ArrayList<Province>();
list.add(p1);
list.add(p2);
list.add(p3);
/***************************转化list到json*************************************/
//方法一
JSONArray jsonArray=(JSONArray)JSONSerializer.toJSON(list);
System.out.println(jsonArray.toString());
//[{"description":"fandong","id":"1","name":"吉林省"},{...
//方法二,过滤属性,没有用的属性转化为json时,不往上面添加
JsonConfig jsonConfig=new JsonConfig();
//1.设置哪些属性不写在json中
jsonConfig.setExcludes(new String[]{"description"});
JSONArray jsonArray1=(JSONArray)JSONArray.fromObject(list,jsonConfig);
System.out.println(jsonArray1.toString());
//[{"id":"1","name":"吉林省"},{"id":"2","name":"山东省"},{"id":"3","name":"辽宁省"}]
/***************************转化javabean到json*************************************/
JSONObject jsonObject=JSONObject.fromObject(p1);
System.out.println(jsonObject.toString());
//{"description":"fandong","id":"1","name":"吉林省"}
/***************************转化json到javabean*************************************/
String jsonStr="{\"id\":\"1\",\"name\":\"吉林省\"}";
//1.把字符串转化为json类型的对象
JSONObject jsonObject1=(JSONObject)JSONSerializer.toJSON(jsonStr);
//2.json对象-->javabean,要求Province类中要有一个无惨的构造函数和一个有参的构造函数
Province pp =(Province)JSONObject.toBean(jsonObject1, Province.class);
System.out.println(pp.getId()+":"+pp.getName());//吉林省
/***************************转化javabean到json*************************************/
}
}
JQuery
例1、DOM对象转化为JQuery对象
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DOMJquery.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="js/jquery.js"></script>
</head>
<body>
<input type="text" value="zhang" name="username" id="username"/>
</body>
<script language="JavaScript"> //dom对象转化为Jquery对象 $(DOM对象) //1.获取DOM对象 var usernameElement=document.getElementById("username"); var valueStr=usernameElement.value; alert(valueStr); //2.dom转化为jquery var $usernameElement=$(usernameElement); alert("*****"+$usernameElement.val()); </script>
</html>
例2、JQuery对象转化为DOM对象
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JqueryDOM.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="js/jquery.js"></script>
</head>
<body>
<input type="text" value="zhang" name="username" id="username"/>
</body>
<script language="JavaScript"> //jquery对象转化为DOM对象 //$usernameElement ---- 是一个JQuery对象 var $usernameElement = $("#username"); alert($usernameElement.val()); //方法一 JQuery对象是一个数组对象,可以通过[index]的方法,来得到相应的DOM对象 var usernameElement1=$usernameElement[0]; alert(usernameElement1.value); //方法二、jquery本身提供通过get(index)方法得到相应的DOM对象 var usernameElement2=$usernameElement.get(0); alert(usernameElement2.value); </script>
</html>
例3、DOM和jquery之间的比较
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DOMJquery.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="js/jquery.js"></script>
</head>
<body>
<input type="text" value="zhang" name="username" id="username"/>
</body>
<script language="JavaScript"> /********************DOM***********************************/ //在javascript中函数的返回值为空,表示false var usernameElement=document.getElementById("username1"); if(usernameElement){ alert(usernameElement.value); }else{ alert("不存在");//弹出不存在 } /********************JQuery***********************************/ alert($("#username1").val());//弹出undefind </script>
</html>
(一) 选择器
1、 五个基本选择器
例1 、五个基本选择器(首先将jquery.js放在工程中)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变id为one的元素的背景色为#0000FF" id="b1"/>
<input type="button" value="改变元素名为div的所有元素的背景色为#00FFFF" id="b2"/>
<input type="button" value="改变class为mini的所有元素的背景色为#FF0033" id="b3""/> <input type="button" value="改变所有元素的背景色为#00FF33" id="b4" />
<input type="button" value="改变所有span元素和id为two的元素的背景色为#3399FF" id="b5"/>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one</div>
<div id="two" class="mini">
id为two class为mini
<div class="mini">class是mini</div>
</div>
<div class="one">
class是one
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<br>
<div id="mover">动画</div>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变id为one的元素的背景色为#0000FF $("#b1").click(function(){ /*css("background","#0000FF") 第一个参数:css中的属性 第二个参数:对应属性的值 */ $("#one").css("background","#0000FF"); }); //2.改变元素名为div的所有元素的背景色为#00FFFF $("#b2").click(function(){ $("div").css("background","#00FFFF"); }); //3.改变class为mini的所有元素的背景色为#FF0033 $("#b3").click(function(){ $(".mini").css("background","#FF0033"); }); //4.改变所有元素的背景色为#00FF33 $("#b4").click(function(){ $("*").css("background","#00FF33"); }); //5.改变所有span元素和id为two的元素的背景色为#3399FF $("#b5").click(function(){ $("span,#two").css("background","#3399FF"); }); </script>
</html>
2、层次选择器
例2、层次选择器
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变body内所有div的背景色为#0000FF" id="b1"/>
<input type="button" value="改变body内子div的背景色为#FF0033" id="b2"/>
<input type="button" value="改变id为one的下一个div的背景色为#0000FF" id="b3""/> <input type="button" value="改变id为two的元素后面的所有兄弟div的元的背景色为#0000FF" id="b4" />
<input type="button" value="改变id为two的元素的所有div兄弟元素的背景色为#0000FF" id="b5"/>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one</div>
<div id="two" class="mini">
id为two class为mini
<div class="mini">class是mini</div>
</div>
<div class="one">
class是one
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<br>
<div id="mover">动画</div>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变body内所有div的背景色为#0000FF $("#b1").click(function(){ $("body div").css("background","#0000FF"); }); //2.改变body内子div的背景色为#FF0033(不包括孙元素) $("#b2").click(function(){ $("body > div").css("background","#FF0033"); }); //3.改变id为one的下一个div的背景色为#0000FF $("#b3").click(function(){ $("#one + div").css("background","#0000FF"); }); //4.改变id为two的元素后面的所有兄弟div的元的背景色为#0000FF $("#b4").click(function(){ $("#two ~ div").css("background","#0000FF"); }); //5.改变id为two的元素的所有div兄弟元素的背景色为#0000FF $("#b5").click(function(){ $("#two").siblings("div").css("background","#0000FF"); }); </script>
</html>
**3.过滤选择器
3.1 基础过滤选择器**
例3、baseFilter_selector.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变第一个div的背景色为#0000FF" id="b1"/>
<input type="button" value="改变最后一个div的背景色为#0000FF" id="b2"/>
<input type="button" value="改变class不为one的所有div的背景色为#0000FF" id="b3""/> <input type="button" value="改变索引值为偶数的div元素的背景色为#0000FF" id="b4" />
<input type="button" value="改变索引值为奇数的div元素的背景色为#0000FF" id="b5" />
<input type="button" value="改变索引值大于3的div元素的背景色为#0000FF" id="b6" />
<input type="button" value="改变索引值等于3的div元素的背景色为#0000FF" id="b7" />
<input type="button" value="改变索引值小于3的div元素的背景色为#0000FF" id="b8" />
<input type="button" value="改变所有标题标元素的背景色为#0000FF" id="b9" />
<input type="button" value="改变当前正在执行动画的所有元素的背景色为#0000FF" id="b10"/>
<div id="mover">动画</div>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one</div>
<div id="two" class="mini">
id为two class为mini
<div class="mini">class是mini</div>
</div>
<div class="one">
class是one
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<br>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变第一个div的背景色为#0000FF $("#b1").click(function(){ $("div:first").css("background","#0000FF"); }); //2.改变最后一个div的背景色为#0000FF $("#b2").click(function(){ $("div:last").css("background","#FF0033"); }); //3.改变class不为one的所有div的背景色为#0000FF $("#b3").click(function(){ $(".one + div").css("background","#0000FF"); }); //4.改变索引值为偶数的div元素的背景色为#0000FF $("#b4").click(function(){ $("div:even").css("background","#0000FF"); }); //5.改变索引值为奇数的div元素的背景色为#0000FF $("#b5").click(function(){ $("div:odd").css("background","#0000FF"); }); //6.改变索引值大于3的div元素的背景色为#0000FF $("#b6").click(function(){ $("div:gt(3)").css("background","#0000FF"); }); //7.改变索引值等于3的div元素的背景色为#0000FF $("#b7").click(function(){ $("div:eq(3)").css("background","#0000FF"); }); //8.改变索引值小于3的div元素的背景色为#0000FF $("#b8").click(function(){ $("div:lt(3)").css("background","#0000FF"); }); //9.改变所有标题标元素的背景色为#0000FF $("#b9").click(function(){ $(":header").css("background","#0000FF"); }); //10.改变当前正在执行动画的所有元素的背景色为#0000FF function ca(){ //.slideToggle("slow");只闪动一下,下面表示连接持续闪动 $("#mover").slideToggle("slow",ca); } //调用函数 ca(); $("#b10").click(function(){ $(":animated").css("background","#0000FF"); }); </script>
</html>
3.2 内容过滤选择器
例4 contentFilter-selector.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变含有文本‘di’的div元素的背景色为#0000FF" id="b1"/>
<input type="button" value="改变不包含子元素(或者文本元素)的div空元素的背景色为#FF0033" id="b2"/>
<input type="button" value="改变含有class为mini元素的div子元素的背景色为#0000FF" id="b3""/> <input type="button" value="改变包含子元素(或者文本元素)的div元素的背景色为#FF0033" id="b4" />
<input type="button" value="改变不含有文本‘di’的div元素的背景色为#0000FF" id="b5"/>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one di</div>
<div id="two" class="mini">
id为two class为mini di
<div class="mini">class是mini</div>
</div>
<div class="one">
class是one
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<div class="one"></div>
<br>
<div id="mover">动画</div>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变含有文本‘di’的div元素的背景色为#0000FF $("#b1").click(function(){ $("div:contains('di')").css("background","#0000FF"); }); //2.改变不包含子元素(或者文本元素)的div空元素的背景色为#FF0033 $("#b2").click(function(){ $("div:empty").css("background","#FF0033"); }); //3.改变含有class为mini子元素的div元素的背景色为#0000FF $("#b3").click(function(){ $("div:has(.mini)").css("background","#0000FF"); }); //4.改变包含子元素(或者文本元素)的div元素的背景色为#FF0033 $("#b4").click(function(){ $("div:parent").css("background","#FF0033"); }); //5.改变不含有文本‘di’的div元素的背景色为#0000FF $("#b5").click(function(){ $("div:not(:contains('di'))").css("background","#0000FF"); }); </script>
</html>
3.3 可见度过滤选择器
例5、可见度过滤选择器
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } div.visible{ display:none; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变所有可见div元素的背景色为#0000FF" id="b1"/>
<input type="button" value="选区所有不可见的元素,利用jquery中的show()方法将他们显示出来,并设置其背景颜色为#0000FF" id="b2"/>
<input type="button" value="选取所有的文本隐藏域,并打印它们的值" id="b3""/> <input type="button" value="选取所有的文本隐藏域,并打印它们的值" id="b4" />
<!-- 文本隐藏域-->
<input type="hidden" value="hidden_1"/>
<input type="hidden" value="hidden_2"/>
<input type="hidden" value="hidden_3"/>
<input type="hidden" value="hidden_4"/>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one di</div>
<div id="two" class="mini">
id为two class为mini di
<div class="mini">class是mini</div>
</div>
<div class="one">
class是one
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="visible">
这是隐藏的!!
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<div class="one"></div>
<br>
<div id="mover">动画</div>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变所有可见div元素的背景色为#0000FF $("#b1").click(function(){ $("div:visible").css("background","#0000FF"); }); //2.选区所有不可见的元素,利用jquery中的show()方法将他们显示出来,并设置其背景颜色为#0000FF $("#b2").click(function(){ $("div:hidden").show().css("background","#0000FF"); }); //3.选取所有的文本隐藏域,并打印它们的值(方法一) $("#b3").click(function(){ //alert($("input:hidden").length); var $inputHidden=$("input:hidden"); /*each:以每一个匹配的元素作为上下文来执行一个函数 * function(index,data) * index:每次遍历的索引0,1,2,3. * data:当前的对象,在循环中等价于this */ $inputHidden.each(function(index,data){ //alert($(this).val()); //alert(index); alert($(data).val()); }); }); //4.选取所有的文本隐藏域,并打印它们的值(方法二) $("#b4").click(function(){ var $inputHidden=$("input:hidden"); /* jQuery.each(obj,callback) * 通用的便利方法,可用于例遍对象和数组 * * 只要是jQuery.xxx方法,就用$.xxx的形式去写 * 第一个参数obj:要遍历的对象和数组 * 第二个参数callback:回调函数 * */ $.each($inputHidden,function(index,data){ alert($(data).val()); }); }); </script>
</html>
3.5属性过滤选择器
例6、属性过滤器
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } div.visible{ display:none; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变含有属性title的div元素的背景色为#0000FF" id="b1"/>
<input type="button" value="改变含有属性title=test的div元素的背景色为#0000FF" id="b2"/>
<input type="button" value="改变含有属性title不为test的div元素的背景色为#0000FF(没有title属的元素也被选中)" id="b3""/> <input type="button" value="改变含有属性title不为test的div元素的背景色为#0000FF(没有title属的元素不被选中)" id="bx""/> <input type="button" value="改变含有属性title以te开头的div元素的背景色为#0000FF" id="b4" />
<input type="button" value="改变含有属性title以est结束的div元素的背景色为#0000FF" id="b5" />
<input type="button" value="改变含有属性title含有es的div元素的背景色为#0000FF" id="b6" />
<input type="button" value="选取含有属性 id 的div元素 然后在结果中选取属性title值含有es的div元素" id="b7" />
<!-- 文本隐藏域-->
<input type="hidden" value="hidden_1"/>
<input type="hidden" value="hidden_2"/>
<input type="hidden" value="hidden_3"/>
<input type="hidden" value="hidden_4"/>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one di</div>
<div id="two" class="mini" title="test">
id为two class为mini di,title="test"
<div class="mini">class是mini</div>
</div>
<div class="one" title="test02">
class是one,title="test02"
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="visible">
这是隐藏的!!
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<div class="one"></div>
<br>
<div id="mover">动画</div>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变含有属性title的div元素的背景色为#0000FF $("#b1").click(function(){ $("div[title]").css("background","#0000FF"); }); //2.改变含有属性title=test的div元素的背景色为#0000FF $("#b2").click(function(){ $("div[title='test']").css("background","#0000FF"); }); //3.改变含有属性title不为test的div元素的背景色为#0000FF(没有title属的元素也被选中) $("#b3").click(function(){ $("div[title!='test']").css("background","#0000FF"); }); //x.改变含有属性title不为test的div元素的背景色为#0000FF(没有title属的元素不被选中) $("#bx").click(function(){ //$("div[title][title!='test']").css("background","#0000FF"); $("div[title]:not([title='test'])").css("background","#0000FF"); }); //4.改变含有属性title以te开头的div元素的背景色为#0000FF $("#b4").click(function(){ $("div[title^='te']").css("background","#0000FF"); }); //5.改变含有属性title以est结束的div元素的背景色为#0000FF $("#b5").click(function(){ $("div[title$='est']").css("background","#0000FF"); }); //6.改变含有属性title含有es的div元素的背景色为#0000FF $("#b6").click(function(){ $("div[title*='es']").css("background","#0000FF"); }); //7.选取含有属性 id 的div元素 然后在结果中选取属性title值含有es的div元素 $("#b7").click(function(){ $("div[id][title*='es']").css("background","#0000FF"); }); </script>
</html>
3.6 子元素选择器
例7、childFilter_selector.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> childFilter_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="改变每一个class为one的div父元素下的第二个子元素的背景色为#0000FF" id="b1"/>
<input type="button" value="改变每一个class为one的div父元素下的第一个子元素的背景色为#0000FF" id="b2"/>
<input type="button" value="改变每一个class为one的div父元素下的最后个子元素的背景色为#0000FF" id="b3""/> <input type="button" value="如果class为one的div父元素下只有一个子元素,改变这个子元素的背景色为#0000FF" id="b4" />
<div id="mover">动画</div>
<h1>天气愣了</h1>
<h2>天气又冷了</h2>
<div id="one">id为one</div>
<div id="two" class="mini">
id为two class为mini
<div class="mini">class是mini</div>
</div>
<div class="one">
class是oneasdfasdf
<div class="mini">class是mini</div>
</div>
<div class="one">
class是one
<div class="mini">class是mini</div>
<div class="mini">class是mini</div>
</div>
<div class="one">
<div class="mini01">class是mini01</div>
<div class="mini">class是mini</div>
</div>
<br>
<br>
<span class="spanone">span</span>
<span class="mini">span</span>
</body>
<script language="javascript"> //1.改变每一个class为one的div父元素下的第二个子元素的背景色为#0000FF $("#b1").click(function(){ //注意:div[class='one']与冒号之间有空格 $("div[class='one'] :nth-child(2)").css("background","#0000FF"); }); //2.改变每一个class为one的div父元素下的第一个子元素的背景色为#0000FF $("#b2").click(function(){ $("div[class='one'] :first-child").css("background","#0000FF"); }); //3.改变每一个class为one的div父元素下的最后个子元素的背景色为#0000FF $("#b3").click(function(){ $("div[class='one'] :last-child").css("background","#0000FF"); }); //4.如果class为one的div父元素下只有一个子元素,改变这个子元素的背景色为#0000FF $("#b4").click(function(){ $("div[class='one'] :only-child").css("background","#0000FF"); }); </script>
</html>
3.8 表单对象属性过滤选择器
例8 表单对象过滤器实例
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
<style type="text/css"> div,span{ width:140px; height:140px; margin:20px; background:#9999cc; border:#000 1px solid; float:left; font-size:17px; font-family:Roman; } div.mini{ width:30px; height:30px; background:#CC66FF; border:#000 1px solid; font-size:12px; font-family:Roman; } </style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="利用jQuery对象的val()方法改变表单内可用<input>元素的值" id="b1"/>
<input type="button" value="利用jQuery对象的val()方法改变表单内不可用<input>元素的值" id="b2"/>
<input type="button" value="利用jQuery对象的length属性获取多选框选中的个数" id="b3""/> <input type="button" value="利用jQuery对象的text()方法获取下拉框选中的内容" id="b4" />
<input type="text" value="不可用值1" disabled="disabled"/>
<input type="text" value="可用值1"/>
<input type="text" value="不可用值2" disabled="disabled"/>
<input type="text" value="可用值2""/> <br> <input type="checkbox" name="items" value="美容">美容
<input type="checkbox" name="items" value="IT">IT
<input type="checkbox" name="items" value="金融">金融
<input type="checkbox" name="items" value="管理">管理
<br>
<input type="checkbox" name="a" value="美容1">美容1
<input type="checkbox" name="a" value="IT1">IT1
<input type="checkbox" name="a" value="金融1">金融1
<input type="checkbox" name="a" value="管理1">管理1
<br>
<input type="radio" name="sex" value="男" checked="checked"/>男
<input type="radio" name="sex" value="女"/>女
<br>
<select name="job" id="job" multiple="multiple" size=4>
<option value="程序员" selected="selected">程序员</option>
<option value="中级程序员">中级程序员</option>
<option value="高级程序员">高级程序员</option>
<option value="系统分析师">系统分析师</option>
</select>
<select name="edu" id="edu">
<option value="本科">本科</option>
<option value="博士">博士</option>
<option value="硕士">硕士</option>
<option value="大专">大专</option>
</select>
<textarea cols=12 rows=4>textarea</textarea>
<button value="确定">确定</button>
</body>
<script language="javascript"> //1.利用jQuery对象的val()方法改变表单内可用<input>元素的值 $("#b1").click(function(){ $("input[type='text']:enabled").each(function(){ $(this).val("可用的值**********"); }); }); //2.利用jQuery对象的val()方法改变表单内不可用<input>元素的值 $("#b2").click(function(){ $("input[type='text']:disabled").each(function(){ $(this).val("不可用的值**********"); }); }); //3.1利用jQuery对象的length属性获取多选框选中的个数 $("#b3").click(function(){ var $ch = $("input[type='checkbox']:checked"); alert($ch.length); }); //3.2利用jQuery对象的length属性获取多选框选中的个数 $("#b3").click(function(){ var $ch = $("input[name='items'][type='checkbox']:checked"); alert($ch.length); }); //4.利用jQuery对象的text()方法获取下拉框选中的内容 $("#b4").click(function(){ $("select option:selected").each(function(index,data){ alert($(this).text()); }); }); </script>
</html>
例9 练习
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>base_selector.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<p>段落1</p>
<p>段落2</p>
<p>段落3</p>
<table border="1">
<tr>
<td>第一行</td><td>第一行</td>
</tr>
<tr>
<td>第二行</td><td>第二行</td>
</tr>
<tr>
<td>第三行</td><td>第三行</td>
</tr>
<tr>
<td>第四行</td><td>第四行</td>
</tr>
<tr>
<td>第五行</td><td>第五行</td>
</tr>
</table>
<br>
<table border="1">
<tr>
<td>第一行</td><td>第一行</td>
</tr>
<tr>
<td>第二行</td><td>第二行</td>
</tr>
<tr>
<td>第三行</td><td>第三行</td>
</tr>
<tr>
<td>第四行</td><td>第四行</td>
</tr>
<tr>
<td>第五行</td><td>第五行</td>
</tr>
</table>
</body>
<script language="javascript"> $("p").each(function(index,data){ $(this).click(function(){ alert($(this).text()); }); }); //将第一个表格的奇数行的北京颜色设置为红色 $("table:eq(0) tr:even").css("background","red"); //将第二个表格的奇数行的北京颜色设置为红色 $("table:eq(1) tr:even").css("background","red"); </script>
</html>
4、DOM操作
例9、
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</style>
</head>
<body>
<input type="button" value="保存" class="mini" name="ok"/>
<input type="button" value="输出li id=bj name=beijing北京</li>name属性的值" id="b1"/>
<input type="button" value="在<ul>中添加<li id=tj name=tianjin>天津</li>" id="b2"/>
<input type="button" value="删除<li id=sh name=shanghai>上海</li>" id="b3""/> <input type="button" value="清空结点<ul>" id="b4" />
<ul id="city">
<li id="bj" name="beijing">北京</li>
<li id="sh" name="shanghai">上海</li>
</ul>
</body>
<script language="javascript"> //1.输出<li id="bj" name="beijing">北京</li>name属性的值 $("#b1").click(function(){ alert($("#bj").attr("name")); }); //2.在<ul>中添加<li id=tj name=tianjin>天津</li> $("#b2").click(function(){ var $li=$("<li></li>"); $li.attr("id","tj"); $li.attr("name","tianjin"); $li.text("天津"); //2.1 append():向每个匹配的元素的内部的结尾处追加内容 //$("#city").append($li);在id=city的元素的最后追加新元素 //2.2 appendTo():将每个匹配的元素追加到指定的元素中的内部结尾处 //$li.appendTo($("#city")); //2.3 prepend():向每个匹配的元素的内部的开始处插入内容 //$("#city").prepend($li); //2.4 prependTo():将每个匹配的元素插入到指定的元素内部的开始处 $li.prependTo($("#city")); }); //3.删除<li id=sh name=shanghai>上海</li> $("#b3").click(function(){ $("#sh").remove(); }); //4.清空结点<ul> $("#b4").click(function(){ $("#city").empty(); //id结点没有删除 alert($("#city").attr("id")); }); </script>
</html>
例10 :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>user.html</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<br><br><br>
<center>
添加用户:<br><br>
用户名:<input type="text" name="username" id="username"/>
电子邮箱:<input type="text" name="email" id="email"/>
电话:<input type="text" name="tel" id="tel"/>
<br><br>
<button id="addUser">提交</button>
</center>
<br><br><br>
<hr>
<center>
<br>
<table border="1" id="user">
<!--这里一定要有tbody标签否则下面appendChild不好使-->
<tbody>
<tr>
<th>用户名</th>
<th>电子邮箱</th>
<th>电话</th>
<th>操作</th>
</tr>
<tr>
<td>fandong</td>
<td>[email protected]</td>
<td>12345</td>
<td><a href="emp?id=fandong">delete</a></td>
</tr>
</tbody>
</table>
</center>
</body>
<script language="JavaScript"> $("#addUser").click(function(){ var nameValue=$("#username").val(); var emailValue=$("#email").val(); var telValue=$("#tel").val(); $tdName=$("<td/>"); $tdName.text(nameValue); $tdEmail=$("<td/>"); $tdEmail.text(emailValue); $tdTel=$("<td/>"); $tdTel.text(telValue); $tdA=$("<td/>"); $a=$("<a/>"); $a.text("delete"); $a.attr("href","delete"); $tdA.append($a); //创建tr $tr=$("<tr/>"); $tr.append($tdName); $tr.append($tdEmail); $tr.append($tdTel); $tr.append($tdA); $("#user").children().eq(0).append($tr); $a.click(function(){ //alert("xx"); deletetr($a); return false; }); }); function deletetr($a){ //1.获取用户名称 var username =$a.parent().parent().children().eq(0).text(); //alert(username); var flag =window.confirm("您真的要删除["+username+"]的值吗?"); //alert(flag); //2.点击取消 if(!flag){ return false;//不再往下执行 } //3.点击确定 //3.1获取tbody $a.parent().parent().remove(); //3.2使连接失效 return false; } /*总结: * children() ********** * 取得一个包含匹配的元素集合中每一个元素的所有子元素的元素集合。 * eq():获取第N个元素,这个元素的位置是从0算起。 * parent():取得一个包含着所有匹配元素的唯一父元素的元素集合。 * */ </script>
</html>
例11、实现选中项的移动
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>select.html</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8"/>
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<select name="select1" size="10" multiple="multiple" id="first">
<option>选项1</option>
<option>选项2</option>
<option>选项3</option>
<option>选项4</option>
<option>选项5</option>
<option>选项6</option>
<option>选项7</option>
<option>选项8</option>
</select>
<input type="button" id="add" value="-->">
<input type="button" id="add_all" value="==>">
<input type="button" id="remove" value="<--">
<input type="button" id="remove_all" value="<==">
<select name="select1" size="10" multiple="multiple" style="width:60" id="second">
</select>
</body>
<script language="JavaScript"> //1.选中的移到右边 $("#add").click(function(){ $("select[id='first'] option:selected").appendTo($("#second")); }); //2.全移动 $("#add_all").click(function(){ $("select[id='first'] option").appendTo($("#second")); }); //3.左边双击移到右边 $("#first").dblclick(function(){ $("select[id='first'] option:selected").appendTo($("#second")); }); </script>
</html>
5.外部插入结点
6、克隆结点
7、替换结点
例12、
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>insert.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<p id="p1">xxxxxxxxxxxx1</p>
<p id="p2">xxxxxxxxxxxx2</p>
<p id="p3">xxxxxxxxxxxx3</p>
<button>保存</button><br><br><br>
<p id="p4">段落</p>
</body>
<script language="JavaScript"> //1.外部插入结点 //1.1.after(content):在每一个匹配的元素之后插入内容 //$("#p3").after($("#p1"));//在p3的后面插入p1 //1.2.before(content):在每一个匹配的元素之前插入内容 //$("#p3").before($("#p1")); //1.3.insertBefore(content)把所有匹配的元素插入到另一个、指定的元素元素集合的前面。 //$("#p1").insertBefore($("#p3")); //1.4.insertAfter(content)把所有匹配的元素插入到另一个、指定的元素元素集合的后面。 //2.克隆结点 // $("button").click(function(){ // alert("xx"); // }); //clone():克隆匹配的DOM元素并且选中这些克隆的副本,但此时复制 的新节点不具有任何行为,不克隆事件 //$("button").clone().appendTo($("#p4")); //clone(true):复制元素的同时也复制元素的事件 //$("button").clone(true).appendTo($("#p4")); //3.替换结点 //将p替换为button $("p").replaceWith("<button>保存1</button>"); //将button替换为p $("p").replaceAll($("button")); </script>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<input type="text" value="用户邮箱/手机号/用户名" id="b1"/><br>
<input type="password" value="" id="b2"/><br>
<input type="button" value="登录" id="b3"/>
</body>
<script language="JavaScript"> //获取焦点 $("#b1").focus(function(){ //alert(this.defaultValue); //1.获取当前值 var curValue=$(this).val(); //2.如果当前值和默认值相同,就置为空 if(curValue==this.defaultValue){ $(this).val(""); } }); //失去焦点 $("#b1").blur(function(){ //1.获取当前值 var curValue=$(this).val(); if($.trim(curValue)==""){ $(this).val(this.defaultValue); } }); </script>
</html>
例14、val()方法详解,取值和赋值
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<input type="button" value="使单选下拉框的2号被选中"/><br>
<input type="button" value="使多选下拉框的2号和4号被选中"/><br>
<input type="button" value="使复选框的复选2和复选4被选中"/><br>
<input type="button" value="使单选框的单选2被选中"/><br>
<input type="button" value="打印已经被选中的值"/><br>
<select id="one">
<option>1号</option>
<option>2号</option>
<option>3号</option>
</select><br>
<select id="mary" multiple="multiple">
<option selected="selected">1号</option>
<option>2号</option>
<option>3号</option>
<option>4号</option>
<option>5号</option>
<option>6号</option>
</select><br>
<input type="checkbox" name="c" value="check1"/>复选1
<input type="checkbox" name="c" value="check2"/>复选2
<input type="checkbox" name="c" value="check3"/>复选3
<input type="checkbox" name="c" value="check4"/>复选4
<br>
<input type="radio" name="r" value="radio1"/>单选1
<input type="radio" name="r" value="radio2"/>单选2
<input type="radio" name="r" value="radio3"/>单选3
</body>
<script language="JavaScript"> //1.使单选下拉框的2号被选中 $("input[type='button']:eq(0)").click(function(){ $("#one").val(["2号"]);//数组 }); //2.使多选下拉框的2号和4号被选中 $("input[type='button']:eq(1)").click(function(){ $("#mary").val(["2号","4号"]); }); //3.使复选框的复选2和复选4被选中 $("input[type='button']:eq(2)").click(function(){ $("input[name='c']").val(["check2","check4"]); }); //4.使单选框的单选2被选中 $("input[type='button']:eq(3)").click(function(){ $("input[name='r']").val(["radio2"]); }); //5.打印已经被选中的值 //5.1 方法1 // $("input[type='button']:eq(4)").click(function(){ // $("#mary option:selected").each(function(index,data){ // alert($(data).text()); // }); // }); //5.2 方法2 $("input[type='button']:eq(4)").click(function(){ $.each($("#mary option:selected"),function(index,data){ alert($(data).text()); }); $("input[name='c']:checked").each(function(index,data){ alert($(data).val()); }); }); </script>
</html>
例15、next()方法举例。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>收缩展开效果</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<!--收缩展开效果-->
<div class="box">
<h1>收缩展开效果</h1>
<div id="menu1">
1<br/>
2<br/>
3<br/>
4<br/>
5<br/>
</div>
</div>
<div id="menu2">
<h1>收缩展开效果</h1>
<div class="text">
1<br/>
2<br/>
</div>
</div>
<div id="menu3">
<h1>收缩展开效果</h1>
<div class="text">
1<br/>
2<br/>
</div>
</div>
<br/>
</body>
<script language="JavaScript"> //1.执行单击事件的域 $("h1").each(function(index,data){ $(data).click(function(){ // slideToggle(1)通过高度变化切换元素的可见性 $(this).next().slideToggle(1);//1ms }); }); </script>
例16、实现下拉列表的显示与隐藏
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="../js/jquery.js"></script>
</head>
<body>
<table>
<tbody>
<!--*************************************************************************************-->
<tr>
<td>
<table width="152">
<tr width="152">
<td>
<table width="98%">
<tr style="color:red;background:blue;cursor:hand" onClick="show('1')">
<td><img src="../image/1.gif"></td>
<td>客户管理1</td>
<td><img src="../image/2.gif"></td>
</tr>
</table>
</td>
</tr>
<tr id="tr0_1" style="display:null">
<td>
<table width="90%" align="center">
<tr>
<td><img src="../image/2.gif"></td>
<td>客户拜访1</td>
</tr>
</table>
<table width="90%" align="center">
<tr>
<td><img src="../image/2.gif"></td>
<td>联系人列表1</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!--*************************************************************************************-->
<tr>
<td>
<table width="152">
<tr width="152">
<td>
<table width="98%">
<tr style="color:red;background:blue;cursor:hand" onclick="show('2')">
<td><img src="../image/1.gif"></td>
<td>客户管理2</td>
<td><img src="../image/2.gif"></td>
</tr>
</table>
</td>
</tr>
<tr id="tr0_2" style="display:none">
<td>
<table width="90%" align="center">
<tr>
<td><img src="../image/2.gif"></td>
<td>客户拜访2</td>
</tr>
</table>
<table width="90%" align="center">
<tr>
<td><img src="../image/2.gif"></td>
<td>联系人列表2</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!--*************************************************************************************-->
<tr>
<td>
<table width="152">
<tr width="152">
<td>
<table width="98%">
<tr style="color:red;background:blue;cursor:hand" onClick="show('3')">
<td><img src="../image/1.gif"></td>
<td>客户管理3</td>
<td><img src="../image/2.gif"></td>
</tr>
</table>
</td>
</tr>
<tr id="tr0_3" style="display:none">
<td>
<table width="90%" align="center">
<tr>
<td><img src="../image/2.gif"></td>
<td>客户拜访3</td>
</tr>
</table>
<table width="90%" align="center">
<tr>
<td><img src="../image/2.gif"></td>
<td>联系人列表</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!--*************************************************************************************-->
</tbody>
</table>
</body>
<script language="JavaScript"> function show(i){ // alert(i); //1.获取所有要操作的tr tr0_n <tr id="tr0_3" style="display:null"> $("tr[id^='tr0']").each(function(index,data){ //如果当前tr if(index+1==i){ if($(data).is(":hidden")){ //是隐藏的,则显示出来 $(data).attr("style","display:null"); }else{ //否则,设置为隐藏 $(data).attr("style","display:none"); } }else{ //其他的全部隐藏 $(data).attr("style","display:none"); } }); } </script>
</html>
10.JQuery表单验证
一、必须引用:
<script language="JavaScript" src="../form/jquery-1.7.2.js"></script>
<script language="JavaScript" src="../form/jquery.validate.js"></script>
二、默认验证规则
(1) required: true 必须输入
(2) number: true 只能输入数字(包括小数)
(3) digits:true 只能输入整数
(4) min: 3 不能小于3
(5) max: 100 最大不超过100
(6) range:[50,100] 值范围为50-100
(7) minLength: 5 最小长度(汉字算一个字符)
(8) maxLength: 10 最大长度(汉字算一个字符)
(9) rangeLength:[5,10] 长度范围为5至10位(汉字算一个字符)
(10) 上面的minLength, maxLength, rangeLength 这三项除了text input之外还可以用于checkbox,select这两种控件
(11) email:true 电子邮件
(12) equalTo: “#field” 与#field值相同
(14)date:true 日期格式:1982/09/21
(13) dateISO:true 日期型,格式为2012/02/12 2010-1-14
(14)remote:”check.php” 必须使用ajax方法调用check.php验证输入值
(15)url:true 必须输入正确的网址
(16)creditcart:true 必须输入正确的信用卡号
(17)accept: 输入拥有合法后缀名的字符串(上传文件的后缀名)
例17、表单验证
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>emp_cn.html</title>
<link rel="stylesheet" type="text/css" media="screen" href="screen.css" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="jquery-1.7.2.js"></script>
<script language="JavaScript" src="jquery.validate.js"></script>
<script type="text/javascript"> $.validator.setDefaults({ submitHandler: function() { //验证完毕提交表单之前要走这个方法、 alert("submitted!"); } }); /* * 自定义验证方法: * $.validator.addMethod(方法名称,调用函数) * * 第一个参数:添加的验证方法的名子, * * 第二个参数: 自定义的错误提示,通常是一个函数 * function(value,element,params) * * value:是元素的值 * * element:元素本身 * * params:参数 */ $.validator.addMethod("checkTest",function(value,element,params){ //alert(value);文本框中的值 if(value==""){ return false;//没有通过 } return true;//通过 }); $().ready(function(){//页面准备好了再执行 //对那个表单进行验证,validate() jquery验证框架的验证方法 $("#empForm").validate({ //rules: 自定义规则,key:value的形式,key是要验证的元素,value可以是字符串或对象 rules: { realname:"required", //realname是元素节点的name属性 username:{ required:true, maxlength:8, minlength:5 }, password1:{ required:true, minlength:5, maxlength:8 }, password2:{ required:true, minlength:5, maxlength:8, equalTo:"#password1" //id }, sex:{ required:true }, age:{ required:true, min:26, max:50 }, edu:{ required:true }, birthday:{ required:true, date:true }, checkbox1:{ required:true }, email:{ required:true, email:true }, description:{ //调用前面定义的方法,这里等价于required=true checkTest:"1" //1表示使用默认信息 } }, //messages:自定义的提示信息key:value的形式key是要验证的元素,值是字符串或函数 /* * 错误提示信息默认放在域的后面 */ messages: { realname:"您的真实姓名不能为空", username:"登录名不能为空,长度在5~8之间", password1:"您的密码不能为空,长度为5~8之间", password2:"您的确认密码不能为空,确认密码必须和密码相等", sex:"必选一个", age:"年龄不能为空,并且必须在26~50之间", edu:"请选择学历", birthday:"您出生日期的格式不对", checkbox1:"必须选中其中一个", email:"您必须输入正确的电子邮件", description:"个人信息描述不能为空" } }); }); </script>
</head>
<body>
<h1> 员工信息录入</h1>
<form id="empForm" name="empForm" action="" method="post">
<table border="1">
<tr>
<td width="200">真实姓名(不能为空)</td>
<td><input id="realname" name="realname" type="text"/></td>
</tr>
<tr>
<td width="200">登录名(登录名不能为空,长度应该在5~8之间):</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password1" id="password1"/></td>
</tr>
<tr>
<td>重复密码:</td>
<td><input type="password" name="password2" id="password2"/></td>
</tr>
<tr>
<!-- jquery.validate.js在处理错误信息时会生成一个标签<label></label> <label style="display:none;" for="sex" class="error">性别必须选中一个1</label> 1.标签名是label 2.标签开始默认是隐藏的 tyle="display:none;" 3.for="sex" 是该标签的唯一标识 4.class="error" 固定写法,标识错误信息 5.验证框架会根据label标签,for属性的值查找该标签是否存在 5.1 如果不存在,即当<label/>在表单中没有定义的时候,验证框架会生成一个<label/>标签,并且增加 for属性值就是标签的name属性的值 5.2 如果存在,即当在表单中定义<label/>的时候,验证框架会根据name属性在表单中查找该标签,然后显示 -->
<td>性别(必选其一)</td>
<td><input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
<label style="display:none;" for="sex" class="error">性别必须选中一个1</label>
</td>
</tr>
<tr>
<td>年龄(必填26~50):</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>你的学历:</td>
<td><select name="edu" id="edu">
<!--注意这里的<option>都必须要有value属性-->
<option value="">--请选择你的学历--</option>
<option value="博士">博士</option>
<option value="硕士">硕士</option>
<option value="本科">本科</option>
<option value="大专">大专</option>
<option value="高中">高中</option>
</select>
</td>
</tr>
<tr>
<td width="200">出生日期(1982/09/21):</td>
<td><input type="text" name="birthday"/></td>
</tr>
<tr>
<td>兴趣爱好:</td>
<td>
<input type="checkbox" name="checkbox1" value="乒乓球"/>乒乓球
<input type="checkbox" name="checkbox1" value="羽毛球"/>羽毛球
<input type="checkbox" name="checkbox1" value="上网"/>上网
<input type="checkbox" name="checkbox1" value="旅游"/>旅游
<input type="checkbox" name="checkbox1" value="购物"/>购物
<label style="display:none;" for="checkbox1" class="error">您的兴趣爱好必须选择一个</label>
</td>
</tr>
<tr>
<td width="200">电子邮箱:</td>
<td><input type="text" name="email"/></td>
</tr>
<!--自定义校验规则-->
<tr>
<td width="200">test:</td>
<td><input type="text" name="description"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</body>
</html>
CREATE TABLE province( pid INT, pname VARCHAR(20) ) SELECT pid,pname FROM province ORDER BY pid CREATE TABLE city( cid INT, cname VARCHAR(20), pid INT #省对应的编号 )
第二步、readme.txt
利用struts和jquery实现三级联动
* 引入类库:
* 引入struts类库
* 引入json类库
* 引入数据库连接驱动
* 引入js文件
* 引入Jquery.js文件
第三步、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>list.html</welcome-file>
</welcome-file-list>
</web-app>
第四步、struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<action-mappings>
<action path="/listAction" parameter="method" type="cn.itcast.web.action.ListAction"></action>
</action-mappings>
</struts-config>
第五步、list.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>list.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="JavaScript" src="./js/jquery-1.7.2.js"></script>
</head>
<body>
<select id="province" name="province">
<option value="">请选择...</option>
</select>
<select id="city" name="city">
<option value="">请选择...</option>
</select>
<select id="county" name="county">
<option value="">请选择...</option>
</select>
</body>
<script type="text/javascript"> $(document).ready(function(){ //1.获取省的信息 //页面一启动就发送请求 $.post("./listAction.do?method=listProvince",function(data,textStatus){ var dataObjs=eval("("+data+")"); for(var i=0;i<dataObjs.length;i++){ var dataObj=dataObjs[i]; //alert(dataObj.pid+":"+dataObj.pname); var $option=$("<option></option>"); $option.attr("value",dataObj.pid); $option.text(dataObj.pname); $("#province").append($option); } }); //2.省的变化引起城市的变化 $("#province").change(function(){ //alert(this.value); $.post("./listAction.do?method=listCity",{'pid':$(this).val()},function(data,textStatus){ //删除city下拉选的内容 $("#city option").each(function(index,data){ if(index!=0){//排除第一项 $(data).remove(); } }); var dataObjs=eval("("+data+")"); for(var i=0;i<dataObjs.length;i++){ var dataObj=dataObjs[i]; //alert(dataObj.cid+":"+dataObjs[i].cname); var $option=$("<option></option>"); $option.attr("value",dataObj.cid); $option.text(dataObj.cname); $("#city").append($option); } }); }); //3.城市的变化引起县城的变化 }); </script>
</html>
第六步、ListAction.java
package cn.itcast.web.action;
public class ListAction extends DispatchAction {
public ActionForward listProvince(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
//1.获取省的信息放置到list中
DaoProvinceImpl daoProvinceImpl=new DaoProvinceImpl();
List<Province> list = daoProvinceImpl.findAllProvince();
//2.将list转化为json格式
JSONArray jsonArray = JSONArray.fromObject(list);
//System.out.println(jsonArray.toString());
//3.输出:out.println(json);
out.println(jsonArray.toString());
return null;
}
public ActionForward listCity(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
String spid=request.getParameter("pid");
Integer pid=Integer.parseInt(spid);
//System.out.println(spid);
DaoCityImpl daoCityImpl=new DaoCityImpl();
//1.获取某个省下面的city的信息放置到list中
List<City> list = daoCityImpl.findAllCity(pid);
//2.将list转化为json格式
JSONArray jsonArray = JSONArray.fromObject(list);
//3.输出:out.println(json);
out.println(jsonArray.toString());
return null;
}
}
第七步、Province.java
package cn.itcast.bean;
public class Province {
private Integer pid;
private String pname;
……
第八步、DaoProvinceImpl.java
package cn.itcast.dao.Impl;
public class DaoProvinceImpl {
public List<Province> findAllProvince() {
List<Province> list=new ArrayList<Province>();
DBManager dbManager=DBManager.getDbManager();
Connection conn=dbManager.getConnection();
PreparedStatement pstatement=null;
ResultSet rs=null;
//SELECT pid,pname FROM province ORDER BY pid
String sql="SELECT pid,pname FROM province ORDER BY pid";
try {
pstatement=conn.prepareStatement(sql);
rs=pstatement.executeQuery();
while(rs.next()){
Province p=new Province();
p.setPid(rs.getInt(1));
p.setPname(rs.getString(2));
list.add(p);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dbManager.closeResource(conn, pstatement, rs);
}
return list;
}
}
第九步、DBManager.java
package cn.itcast.db;
public class DBManager {
private static DBManager dbManager=new DBManager();
private BasicDataSource bds=null;
private DBManager(){
bds=new BasicDataSource();
bds.setUsername("root");
bds.setPassword("root");
bds.setUrl("jdbc:mysql://localhost:3306/test");
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setMaxActive(5);
bds.setInitialSize(4);
bds.setMinIdle(3);
bds.setMaxIdle(10);
bds.setMaxWait(5000);
}
public static DBManager getDbManager(){
return dbManager;
}
public Connection getConnection(){
Connection conn=null;
try {
conn=bds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void closeResource(Connection conn,Statement statement,ResultSet rs){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
}
第十步、City.java
package cn.itcast.bean;
public class City {
private Integer cid;
private String cname;
……
第十一步、DaoCityImpl.java
package cn.itcast.dao.Impl;
public class DaoCityImpl {
public List<City> findAllCity(Integer pid) {
List<City> list=new ArrayList<City>();
DBManager dbManager=DBManager.getDbManager();
Connection conn=dbManager.getConnection();
PreparedStatement pstatement=null;
ResultSet rs=null;
//SELECT pid,pname FROM province ORDER BY pid
String sql="SELECT cid,cname FROM city where pid=? ORDER BY cid";
try {
pstatement=conn.prepareStatement(sql);
pstatement.setInt(1, pid);
rs=pstatement.executeQuery();
while(rs.next()){
City c=new City();
c.setCid(rs.getInt(1));
c.setCname(rs.getString(2));
list.add(c);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dbManager.closeResource(conn, pstatement, rs);
}
return list;
}
}