第一章:入门
选择元素:
$()
css()
$("li").css():可以省略原生的循环操作
$ == jQuery
jQuery方法函数化:
click()
html()
JS与jQ关系:
可以共存,不能混写
函数中this是原生的,$(this)转换为jQ对象
点击变色例子:
<!DOCTYPE html> <html> <head> <title></title> <style> div{ width: 100px; height: 100px; float: left; border: 1px solid #333; } </style> </head> <body> <span>red</span> <span>blue</span> <span>green</span> <span>yellow</span> <br> <div></div> <div></div> <div></div> <div></div> <script src="jquery-1.11.1.js"></script> <script> var color = ''; $('span').click(function(){ color = $(this).html(); }); $('div').click(function(){ $(this).css('backgroundColor',color); }); </script> </body> </html>
取值与赋值:
取值或赋值通过参数个数来决定,html(),attr(),val()
多元素取值,取到的是选中元素的第一个
$("input[value^=123]").css():value值以123为起始的元素
强大的$():
加载--
$(function(){ ... });
属性选择--
[=] [^=]开始 [$=]结束 [*=]包含
引号的问题:
[class = box1]
[class = "box1 box2"]
jQ的链式操作:
$().css().html().click()...
链式操作是针对设置的时候,获取操作的时候是不行的
jQ实战小技巧:
命名的规范--
$span/$div
容错处理--
$()找不到的元素不报错
集合的长度:
$('div').size()
$('div').length
$()获取到的都是一个集合,例如$('#div1').length的长度为1
jQ实战小技巧:
利用length判断元素是否存在,length == 0 则不存在
去掉指定颜色的方块颜色:属性选择器练习
<!DOCTYPE html> <html> <head> <title></title> <style> div{ width: 100px; height: 100px; float: left; border: 1px solid #333; } </style> </head> <body> <span>red</span> <span>blue</span> <span>green</span> <span>yellow</span> <br> <input type="button" value="clear red"> <br> <div></div> <div></div> <div></div> <div></div> <script src="jquery-1.11.1.js"></script> <script> var color = ''; $('span').click(function(){ color = $(this).html(); }); $('div').click(function(){ $(this).css('backgroundColor',color); }); $('input').click(function(){ $('div[style *= red]').css('backgroundColor',''); }); </script> </body> </html>
class的操作:
addClass()
removeClass()
toggleClass()自动判断该add还是remove
以上也和运用attr实现
显示与隐藏:
show()/hide()
与css()显示隐藏的区别:显示行内元素后可能变成block或inline-block,改变原来的默认值
节点的选择:
prev()/next()
prevAll()/nextAll()
siblings() 参数的筛选功能
jQ实战小技巧:
nextAll('.box')//利用参数修复查找结点问题
下标:
eq()
抽奖效果:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } ul{ width: 366px; overflow: hidden; } li{ float: left; width: 100px; height: 100px; margin: 10px; border: 1px solid #333; list-style-type: none; } .on{ background-color: red; } </style> </head> <body> <input type="button" value="start"> <ul> <li>一等奖</li> <li>二等奖</li> <li>三等奖</li> <li>四等奖</li> <li>五等奖</li> <li>六等奖</li> <li>七等奖</li> <li>八等奖</li> <li>九等奖</li> </ul> <script src="jquery-1.11.1.js"></script> <script> var iNow = 0; var timer = null; var $li = $('li').length; $('input').click(function(){ var step = parseInt(Math.random() * 20 + 5);//5-24 timer = setInterval(function(){ $('li').eq(iNow).attr('class','on').siblings().attr('class',''); iNow ++; //通过判断一个随机数为0时停止定时器 step --; if(step == 0){ clearInterval(timer); alert('恭喜你抽中了'+$('li[class = on]').html()); } if(iNow == $li){ iNow = 0; } },200); }); </script> </body> </html>
第二章:上手
节点的选择:
first()
last()
slice(start,end)截取选中集合对象的一部分,包括起始位置不包括结束位置,不写end默认到最后
children()一级子节点
$('div').find('a')找div中为a的后代节点
parent()父节点
parents('body')祖先节点
closest()重要!必须要接受一个参数,找离当前节点最近的唯一一个祖先元素也包括自身
实战小技巧:
$('ul').find('p')性能高,推荐
$('ul p')
创建节点:
$('<div id="div1"></div>')
添加节点:
insertBefore() before()把元素添加到指定节点的前面
insertAfter() after()把元素添加到指定节点的后面
appendTo() append()把元素添加到指定节点里面的最后
prependTo() prepend()把元素添加到指定节点里面的最前
两种添加方式的区别是对后续操作的对象不同,例如:
$("ul").append($li).css('background','red')ul变红
$li.appendTo($("ul")).css('background','red')li变红
实战小技巧:
var $li = $('<li class="box">hello</li>');
$('ul').append($li)
$li.click(...);
节点的操作:
节点操作不仅可以针对新创建的元素,也可以是页面中已存在的元素
append()等也可对页面已存在的元素进行操作(剪切)
remove()
clone()默认只克隆元素结构,不克隆事件
clone(true)克隆之前的操作行为,像事件
节点的上移下移
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } input{ width: 50px; } </style> </head> <body> <div id="wrap"> <div>00000000001<input type="button" value="up"></input><input type="button" value="down"></input></div> <div>00000000002<input type="button" value="up"></input><input type="button" value="down"></input></div> <div>00000000003<input type="button" value="up"></input><input type="button" value="down"></input></div> <div>00000000004<input type="button" value="up"></input><input type="button" value="down"></input></div> <div>00000000005<input type="button" value="up"></input><input type="button" value="down"></input></div> <div>00000000006<input type="button" value="up"></input><input type="button" value="down"></input></div> </div> <script src="jquery-1.11.1.js"></script> <script> $(function(){ $("input[value=up]").click(function(){ var iNow = $(this).parent(); var iUp = $(this).parent().prev(); //iUp.length == 0 if(iNow.get(0) == iNow.parent().children().eq(0).get(0)){ alert('到头了'); } else{ iNow.insertBefore(iUp); } }); $("input[value=down]").click(function(){ var iNow = $(this).parent(); var iDown = $(this).parent().next(); if(iDown.length == 0){ alert('到尾了'); } else{ iNow.insertAfter(iDown); } }); }); </script> </body> </html>
jQ中的索引:
index()当前元素在兄弟节点(与标签类型无关)中的排行,也可筛选index('p')
$('#span1').index('div span')筛选后的排行,这些span不一定是兄弟关系,所有div中的span
$('div span').index($('#span1'))和上面写法一样
选项卡
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } input{ width: 60px; } #wrap div{ width: 200px; height: 200px; border: 1px solid #333; display: none; } #wrap .active{ display: block; } .on{ background-color: yellow; } </style> </head> <body> <div id="wrap"> <input class="on" type="button" value="一"> <input type="button" value="二"> <input type="button" value="三"> <div class="active">1</div> <div>2</div> <div>3</div> </div> <script src="jquery-1.11.1.js"></script> <script> $(function(){ $("#wrap").find("input").click(function(){ $(this).addClass('on').siblings().removeClass('on'); $('#wrap div').eq($(this).index()).addClass('active').siblings().removeClass('active'); }); }); </script> </body> </html>
jQ中的遍历each():
$('li').each(function(i,elem){//索引,原生的元素
$(elem).html(i);
$(this).html(i);
this == elem
if(i == 2){
return false;//跳出循环
}
});
jQ包装对象:
wrap()----$('span').wrap('<div></div>')span外包个div
wrapAll()
wrapInner()
unwrap()删除包装相当于删除父节点,body是不能被删的
管理员与普通用户状态控制
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <input type="button" value="管理员"> <input type="button" value="普通用户"> </div> <div> <span>登陆</span> </div> <script src="jquery-1.11.1.js"></script> <script> $(function(){ $("input[value=管理员]").click(function(){ $("span").wrap('<a href="javascript:;"></a>'); }); $("input[value=普通用户]").click(function(){ $("span").unwrap('<a href="javascript:;"></a>'); }); }); </script> </body> </html>
jQ对象转原生对象:
$('div').get()
$('div')是一个集合,$('div').get()是一个原生集合
$('div').get(0) == $('div')[0]
为什么转?
>>获取内容的高度scrollHeight
>>元素之间的比较$nowLi.get(0) == $li.eq(0).get(0) 上移下移的例子
[] == [] false
{} == {} false 引用不同
左右切换数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } li{ list-style-type: none; line-height: 1.5; cursor: pointer; margin-top: 10px; } .wrap{ margin: 50px auto 0; width: 600px; overflow: hidden; border: 1px solid #333; } .left{ float: left; width: 255px; padding-left: 20px; } .center{ float: left; width: 50px; } .center span{ margin-top: 50px; display: block; height: 48px; line-height: 48px; border: 1px solid #333; cursor: pointer; text-align: center; } .right{ float: left; width: 255px; padding-left: 20px; } .active{ background-color: green; color: #fff; } </style> </head> <body> <div class="wrap"> <div class="left"> <ul id="left-list"> <li>这是列表1</li> <li>这是列表2</li> <li>这是列表3</li> <li>这是列表4</li> <li>这是列表5</li> <li>这是列表6</li> <li>这是列表7</li> <li>这是列表8</li> </ul> </div> <div class="center"> <p><span id="right" from="#left-list" to="#right-list">></span></p> <p><span id="left" from="#right-list" to="#left-list"><</span></p> </div> <div class="right"> <ul id="right-list"> <li>这是列表1</li> <li>这是列表2</li> <li>这是列表3</li> <li>这是列表4</li> <li>这是列表5</li> <li>这是列表6</li> <li>这是列表7</li> <li>这是列表8</li> </ul> </div> </div> <script src="jquery-1.11.1.js"></script> <script> $(function(){ $("li").click(function(){ $(this).toggleClass("active"); }); // $("#right").click(function(){ // var $li = $("#left-list li[class=active]"); // $li.appendTo($("#right-list")).attr("class",""); // }); // $("#left").click(function(){ // var $li = $("#right-list li[class=active]"); // $li.appendTo($("#left-list")).attr("class",""); // }); $('span').click(function(){ $($(this).attr('from')).find('.active').appendTo( $($(this).attr('to')) ).removeClass('active'); }); }); </script> </body> </html>
评分效果:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .list{ margin: 50px auto 0; width: 300px; overflow: hidden; } .list li{ width: 38px; height: 38px; float: left; border: 1px solid #333; margin: 10px; list-style-type: none; cursor: pointer; } .list li.active{ background-color: red; } </style> </head> <body> <ul class="list"> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <script src="jquery-1.11.1.js"></script> <script> $(function(){ // var bBtn = true; // var timer = null; // $("li").mouseover(function(){ // if(bBtn){ // clearTimeout(timer); // var index = $(this).index(); // $("li").each(function(i,ele){ // if(i <= index){ // $(this).addClass('active'); // } // else{ // $(this).removeClass('active'); // } // }); // } // }).mouseout(function(){ // if(bBtn){ // timer = setTimeout(function(){ // $('li').removeClass('active'); // },100); // } // }).click(function(){ // bBtn = false; // }); var bBtn = true; var timer = null; $("li").mouseover(function(){ if(bBtn){ clearTimeout(timer); $("li").slice(0,$(this).index()+1).addClass("active"); $("li").slice($(this).index()+1).removeClass("active"); } }).mouseout(function(){ if(bBtn){ timer = setTimeout(function(){ $('li').removeClass('active'); },100); } }).click(function(){ bBtn = false; }); }); </script> </body> </html>
第三章:突破
元素的尺寸:
width()/height() width
innerWidth()/innerHeight() width+padding
outerWidth()/outerHeight() widht+padding+border
outerWidth(true) width+padding+border+margin
原生JS是获取不到隐藏元素尺寸的,jQ则可以
实战小技巧:
可视区的尺寸$(window).height()
页面的尺寸$(document).height()
滚动距离:
$(document).scrollTop()
$(document).scrollLeft()
当页面滚动到最底部时:$(document).scrollTop() == $(document).height() - $(window).height()
设置滚动距离:$(document).scrollTop(0);
元素滚动(条)距离:$("#div1").scrollTop()
元素距离:
offset().left:相对于document而非可视区,与其父元素有无定位无关
原生:offsetLeft到达有定位的父级
position().left到有定位的父级,不包含自身的margin值
实战小技巧:
offsetParent()获取有定位的父级
目的:不管有无margin获取到有定位父级的值
$('#div2').offset().left - $('#div2').offsetParent().offset().left
懒加载页面中的图片:img.offset().top < $(window).height() + $(document).scrollTop()
toChange(); $(window).scroll(toChange); function toChange(){ $('img').each(function(i,elem){ if( $(elem).offset().top < $(window).height() + $(document).scrollTop() ){ $(elem).attr('src' , $(elem).attr('_src') ); } }); }
事件:
on()
off()
jQ中事件操作都是绑定的形式
支持多事件写法
click()写法,也是采用off()取消
even对象:
ev.pageX鼠标x轴坐标,相对于整个页面document
ev.clientX鼠标x轴坐标,相对于可视区
$(document).keydown(function(ev){
ev.which 键盘键值
ev.stopPropagation() 阻止冒泡
ev.preventDefault() 阻止默认事件,例如contextmenu()右键菜单
return false 阻止默认事件和冒泡
});
$(document).click(function(ev){
//当前目标元素事件源
alert(ev.target);
});
实战小技巧:
//点多次#div1的时候会多次调用$('#span1').click(),此时再点#span1会执行多次弹窗,解决:
$('#div1').click(function(){
$('#span1').off('click').click(function(){//第一次点span为什么没反应呢?
alert(1);
});
});
拖拽小例子:
$div = $("#div1"); $div.mousedown(function(ev){ var $x = ev.pageX - $(this).offset().left; var $y = ev.pageY - $(this).offset().top; $(document).mousemove(function(ev){ $div.css({ "left" : ev.pageX - $x, "top" : ev.pageY - $y }); }).mouseup(function(){ $(document).off(); }); return false; });
事件委托:
//事件委托,对新添加的元素依然有效
$('ul').delegate('li','click',function(){
$(this) 指li
$(ev.delegateTarget) 指ul
$(ev.delegateTarget).undelegate() 取消委托
});
主动触发:
$('input').kedown(function(){
if(ev.which == 13){
//两种写法
$('#btn').trigger('click');
$('#btn').click();
}
});
$('#btn').trigger('click.abc') 命名空间
$('#btn').off('.abc') off可以只写命名空间
例如拖拽中:$(this).off('mousemove.drag').off('mouseup.drag')或$(this).off('.drag')
回车模仿按钮主动触发实例
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> #div1{ width:100px; height:100px; background:red; position:absolute; left:100px; top:100px;} </style> <script src="jquery-1.11.1.js"></script> <script> //trigger() : 主动触发 $(function(){ $('ul').delegate('li','click',function(ev){ $(this).css('background','red'); }); $('#input1').click(function(){ var $li = $('<li>'+ $('#input2').val() +'</li>'); $('ul').append( $li ); }); $('#input2').keydown(function(ev){ if( ev.which == 13 ){ $('#input1').trigger('click'); //$('#input1').click(); } }); }); </script> </head> <body style="height:2000px;"> <input id="input1" type="button" value="添加"><input id="input2" type="text"> <ul> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> </ul> </body> </html>
工具方法:
既可以给jQ对象用也可以给原声JS用
$.type()比原生强大,能判断对象类型
$.isFunction()
$.inNumeric()判断是否是数字例如'123'是true,不判断类型
$.isArray()
$.inWindow()
$.isEmptyObject()
$.isPlainObject()
$.extend():
默认浅拷贝,支持多对象拷贝
$.extend(b,a) a拷贝一份给b
$.extend(c,b,a) a和b复制一份给c,互不影响
$.extend(true,b,a) 深拷贝
$.proxy():
function show(num){
alert(num);
lert(this);
}
$.proxy(show,document)() //show函数中的this指document,后面加括号才能调用
$.proxy(show,document)(3,4) //调用并传参
$.proxy(show,document,3,4) //传参
$.proxy()灵活设计传参的意义:
$(document).on('click',show); //this指向document
$(document).on('click',$.proxy(show,window)(3));//this指向window,不点就触发了
$(document).on('click',$.proxy(show,window,3));//this指向window,点击后触发
实战小技巧:
利用This改指向,jQuery中使用$(This),更加方便!
登陆弹窗效果练习
第四章:进阶
运动:
show()/hide()/toggle()
fadeIn()/fadeOut()/fadeToggle()
slideDown()/slideUp()/slideToggle()
animation():
默认400毫秒,swing(慢快慢)
animate({ ... },400,swing,function(){ ... })
另一种书写形式的意义:step的使用
$("div").animate({
width:300,
height:300
},{
duration:1000,
easing:'linear',
complete:function(){ ... },
step:function(a,b){ ... }a可以检测定时器的每一次变化 b.pos运动过程的比例值(0,1),起点0,终点1
});
每次点击+=100
width:"+=100"
利用step实现0在2s内运动到843264328
$("#div1").animate({
num: "move"//这里必须要有值,随便写
},{
duration: 2000,
easing: 'linear',
complete: function(){},
step:function(a,b){
$('#div1').html(parseInt(b.pos * 843264328));//b.pos开始的时候是0,结束的时候是1
}
});
运动队列:
运动是异步的不会影响后续非同一对象animation代码,链式运动,同一对象中的运动代码则会存到运动队列中依次执行
$('#div1').animate({width:300},1000);//先运行
$('#div1').animate({height:300},1000);//再运行
$('#div1').animate({left:300},1000);//最后运行
以上代码等同于:
$('#div1').animate({width:300},1000).animate({height:300},1000).animate({left:300},1000);
delay(1000) 停一秒
stop() 默认停止当前一次的运动,直接停那,不是目标点
stop(true) 停止所有运动
stop(true,true) 第二个参数停止当前运动到目标点
finish() 所有运动停到目标点
实战小技巧:
stop()还有一个清空队列的作用
$(this).stop().animation( ... );
解决快速移入移出的问题
$('#div1').mouseover(function(){
$(this).stop().animate({
width:200,
height:200
});
}).mouseout(function(){
$(this).stop().animate({
width:100,
height:100
});
});
淘宝轮播图实例
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>淘宝幻灯滑入滑出效果</title> <style> * { padding: 0; margin: 0; } li { list-style: none; } img { border: none; } body { background: #ecfaff; } #play { width: 470px; height: 150px; overflow: hidden; border: 1px solid #d8d8d8; margin: 100px auto 0; } .packet { width:470px; height: 150px; position: relative; overflow:hidden;} ol { position: absolute; right: 5px; bottom: 5px; z-index: 2; } ol li { float: left; margin-right: 3px; display: inline; cursor: pointer; background: #fcf2cf; border: 1px solid #f47500; padding: 2px 6px; color: #d94b01; font-family: arial; font-size: 12px; } .active { padding: 3px 8px; font-weight: bold; color: #ffffff; background: #ffb442; position: relative; bottom: 2px; } ul { position: absolute; top: 0px; left: 0px; z-index: 1; background:white; width: 470px; height: 150px; } ul li { position:relative; width: 470px; height: 150px; top:0px; left:0px; } ul img { float: left; width: 470px; height: 150px; } </style> <script src="jquery-1.11.1.js"></script> <script> $(function(){ var $olLi = $(".packet ol").find("li"); var $ul = $(".packet ul"); var $liHeight = $ul.find("li").eq(0).height(); var index = 0; var iNow = 0; var timer = null; var $wrap = $('.packet'); $olLi.mouseover(function(){ iNow = index = $(this).index(); $(this).addClass("active").siblings().removeClass("active"); $ul.stop().animate({//停止上次运动再开始新的运动 top: -$liHeight*index },1000); }); var timer= setInterval(move,2000); $wrap.mouseover(function(){ clearInterval(timer); }).mouseout(function(){ timer= setInterval(move,2000); }); function move(){ $olLi.eq(iNow).addClass("active").siblings().removeClass("active"); $ul.stop().animate({//停止上次运动再开始新的运动 top: -$liHeight*iNow },1000); iNow ++; if(iNow == $olLi.length){ iNow = 0; } } }); </script> </head> <body> <div id="play"> <div class="packet"><!-- 为了消除offsetXXX的兼容性问题 --> <ol> <li class="active">1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ol> <ul> <li><a href="http://www.miaov.com/"><img src="img/1.jpg" alt="广告一" /></a></li> <li><a href="http://www.miaov.com/"><img src="img/2.jpg" alt="广告二" /></a></li> <li><a href="http://www.miaov.com/"><img src="img/3.jpg" alt="广告三" /></a></li> <li><a href="http://www.miaov.com/"><img src="img/4.jpg" alt="广告四" /></a></li> <li><a href="http://www.miaov.com/"><img src="img/5.jpg" alt="广告五" /></a></li> </ul> </div> </div> </body> </html>
工具方法:
$.parseJSON() 把严格json类型的字符串转换为真正的json数据
$.parseHTML() 转换HTML形式的字符串,转成DOM节点,放到一个数组中
$.parseXML()
$.isXMLDoc()
$.ajax()
//js
$('#input1').on('input',function(){ $.ajax({ url:'user.php', type:'get',//get形式的传值也可以拼接到url的后面 data:{//往后端传值,也可通过拼接字符串形式传值 user:$(this).val() },
dataType:'json',//规定返回类型必须是json或数组格式的字符串,成功返回时相当于会自动$.parseJSON(data) success:function(data){//返回1的时候可注册返回0不可注册,data为后端返回的值 if(data == 1){ $("#div1").html('可以注册'); } else if(data == 0){ } },
error:function(err){
console.log(err);
} }); });
//php if($_GET['user'] == 'miaov'){ echo '0'; } else{ echo '1'; }
//html <form action="reg.php"> <input type="text" id="input1"> <input type="submit" value="提交"> </form>
async:
$.ajax({ url:'test.php', async:false,//同步,先走ajax再走下面代码 success:function(data){ console.log(data); } }); console.log(123); <?php echo 'hello'; ?>
同步应用场景:
var arr = $.ajax({ url:'test.php', async:false }).responseText; arr = eval(arr); arr.push("hello"); console.log(arr); <?php echo '["a","b","c"]'; ?>
$.get()/$.post() 不能设置同步/异步,$.ajax()的一种简写形式
$.get(
'test.php',
{name:"hello"},//后台通过name接受hello
function(){ ... },//成功回调
'json'//指定返回数据格式,dataType
).error(function(err){ ... });
ajax版本的选项卡实例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } #wrap{ width: 300px; margin: 40px auto 0; } #wrap div{ width: 300px; height: 300px; line-height: 300px; text-align: center; font-size: 30px; color: green; border: 1px solid #333; display: none; } #wrap div.on{ display: block; } input{ width: 60px; height: 30px; } .active{ background-color: yellow; } </style> </head> <body> <div id="wrap"> <input type="button" value="按钮1" class="active"> <input type="button" value="按钮2"> <input type="button" value="按钮3"> <div class="on">1正在加载中...</div> <div>2正在加载中</div> <div>3正在加载中</div> </div> <script src="jquery-1.11.1.js"></script> <script> var index = 0; var $div = $('#wrap').find('div'); $("input").click(function(){ index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $div.eq(index).addClass('on').siblings('div').removeClass('on'); getData(index); }); getData(index); function getData(index){ $.ajax({ url:'data.php?num=' + index, success:function(data){ $div.eq(index).html(data); } }); } </script> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } #wrap{ width: 300px; margin: 40px auto 0; } #wrap div{ width: 300px; height: 300px; line-height: 300px; text-align: center; font-size: 30px; color: green; border: 1px solid #333; display: none; } #wrap div.on{ display: block; } input{ width: 60px; height: 30px; } .active{ background-color: yellow; } </style> </head> <body> <div id="wrap"> <input type="button" value="按钮1" class="active"> <input type="button" value="按钮2"> <input type="button" value="按钮3"> <div class="on">1正在加载中...</div> <div>2正在加载中</div> <div>3正在加载中</div> </div> <script src="jquery-1.11.1.js"></script> <script> var index = 0; var $div = $('#wrap').find('div'); $("input").click(function(){ index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); $div.eq(index).addClass('on').siblings('div').removeClass('on'); loadData(index,function(a){ $div.eq(index).html(a); }); }); loadData(0,function(a){ $div.eq(0).html(a); }) function loadData(index,fn){ $.ajax({ url:'data.php?num=' + index, success:function(data){ fn(data); } }); } </script> </body> </html>
//data.php
<?php if($_GET['num']==0){ echo '第一项的内容'; } else if($_GET['num']==1){ echo '第二项的内容'; } else if($_GET['num']==2){ echo '第三项的内容'; } ?>
优酷电影频道轮播图
//html
<textarea id="t1"></textarea> <input id="input1" type="button" value="发布"> <ul> <li mainId='124346346'><span>1111111111111内容</span> <span class="close">X</span></li> <li mainId='124342222'><span>222222222222内容</span> <span class="close">X</span></li> <li mainId='1243465555'><span>333333333333内容</span> <span class="close">X</span></li> </ul> <input id="input2" type="button" value="载入更多">
/*添加*/ $('#input1').click(function(){ $.ajax({ url : 'add.php', type : 'POST', data : {val:$('#t1').val()}, dataType : 'json', success : function(data){ var $li = $('<li>'); var mainId = data.mainId; $li.html('<span mainId="'+ mainId +'">'+ data.text +'</span> <span class="close">X</span>'); $('ul').prepend( $li ); } }); });
/*删除*/
$('ul').delegate('span.close','click',function(){
var $elem = $(this);
$.ajax({
url : 'remove.php',
data : {'mainId' : $elem.attr('mainId') },
success : function(data){
$elem.parent().remove();
}
});
});
/*查看更多*/ var iNow = 0; $('#input2').click(function(){ iNow++; $.ajax({ url : 'loadPage.php?num='+iNow, dataType : 'json', success : function(data){ for(var i=0;i<data.length;i++){//data是一个数组 var $li = $('<li>'); var mainId = data[i].mainId; var text = data[i].text; $li.html('<span mainId="'+ mainId +'">'+text +'</span> <span class="close">X</span>'); $('ul').append( $li ); } } }); });
扩展练习:寻路
jQ插件:
分为功能型和效果型
$.browser()//判断浏览器类型
$.cookie()//存在跨域不能使用线上地址,下载下来使用
e-calendar()//日历
UI组件:
jQuery UI
jQuery EasyUI
第五章:高级
清空内容:
html("")
empty()
删除节点:
remove() $div = $("#div1").detach();重新添加时不保留行为(事件操作)
detach() $div = $("#div1").detach(); 重新添加到页面时$div将仍会保留行为
text():
$("div").text():获取的是集合的所有文本而非仅第一个
text('<h1>标题</h1>')不解析
替换节点:
$("#span1").replaceWith( $("#div1") )用div替换span,#span1中存在的内容也会消失
replaceAll()上面的不同写法
hover():
mouseenter()和mouseleave()的结合
子元素不会影响父元素:
<div id="div1"> <div id="div2"></div> </div>
$("#div1").mouseover(function(){
$("#div2").animate({//移动到里面div会触发$("#div1").mouseout同时冒泡会触发$("#div1").mouseover
"top":0
});
}).mouseout(function(){
$("#div2").animate({
"top":-100
});
});
$("#div1").mouseenter(function(){
$("#div2").animate({
"top":0
});
}).mouseleave(function(){
$("#div2").animate({
"top":-100
});
});
focusin()/focusout():
focusin()/focusout()会冒泡,子元素中有input时也可给父级加此类事件
focus()/blur()不会冒泡,只能加给有获取焦点的元素
one():
只会触发一次,也可用on后然后再off()模拟
on():
//事件只会作用于span上,相当于下面的delegate写法
$("#div1").on('click','span',{"name":"xiaoyang"},function(ev){
console.log(ev.data);//{"name":"xiaoyang"}
//this指向span
});
$("#div1").delegate('span','click',function(){
});
jQ event转原生event:
ev.changedTouches
ev.originalEvent.changedTouches
自定义事件:
$("#div1").on('zoomIn',function(){
$(this).css('fontSize',12);
});
$("#div1").on('zoomOut',function(){
$(this).css('fontSize',120);
});
$("#div1").on('DOMMouseScroll',function(ev){
if(ev.originalEvent.detail > 0){
$(this).trigger('zoomIn');//当然也可以直接把代码写在这里;自定义事件适合代码合并优化,多人协作时使用
}
else{
$(this).trigger('zoomOut');
}
});
triggerHandler():
trigger()会触发默认行为,例如focus时的光标效果
triggerHandler()不会触发默认行为,例如触发focus时的光标则不会激活;不会冒泡到父元素的trigger事件,相当于阻止了冒泡
ev.stopImmediatePropagation():
ev.stopPropagation()阻止父级行为
ev.stopImmediatePropagation()阻止自身和父级行为,本身的事件操作要放到父级的后面
ev.which:
鼠标键值,mousedown或mouseup时
加载:
$(document).ready(function(){ ... });dom结构加载完,图片可能还没加载
$(window).load(function(){ ... });页面加载完
获取图片宽度时,两个会有差异,解决:使用$(window).load()或者$('img').load(function(){ ... })
选择元素截止到:
parentsUntil()截至到祖先节点的某一个,不包括某一个
nextUntil()下面兄弟节点截至位置
prevUntil()上面兄弟节点截至位置
data()/attr()/prop():
$("#div1").data('name','hello');//存到了一个大的集合中,jQ源码中。缓存大量数据用data()可以防止内存泄漏
$("#div1").data('name');
$("#div1").attr('name','hello');//通过setAttribute()设置在dom结构本身上,通常设置class、title
$("#div1").attr('name');
$("#div1").prop('name','hello');//通过./[]设置在dom结构本身上
$("#div1").prop('name');
removeData()
removeAttr()
removeProp()
全选例子
//aInput[i].checked = true;
//setAttibute('checked','checked');
$(function(){
var bBtn = true;
$('input[type=button]').click(function(){
if(bBtn){
$('input').slice(1).prop('checked',true);//$('input').slice(1)选中索引1往后的所有input
}
else{
$('input').slice(1).prop('checked',false);
}
bBtn = !bBtn;
});
});
json形式的设置:
on({
'click':function(){ ... },
'mouseover':function(){ ... }
})
css()
attr()
回调形式的设置:
addClass()
html()
val()
$("div").addClass(function(i,oldClass){//索引、oldClass
return oldClass + (i+1);
});
工具方法:
$.merge(a,b)合并两个数组
var arr = ['a','b','c','d'];
arr = $.map(arr,function(val,i){
return val+i;
//return 'hello';//数组中所有值变成hello
});
console.log(arr);//["a0", "b1", "c2", "d3"]
var arr = [1,5,4,8,3];
arr = $.grep(arr,function(val,i){
return val > 4;//需要返回一个布尔值
});
console.log(arr);//[5,8]
//$.unique()//只是针对dom节点的去重
var aDiv = $('div').get();
var arr = [];
for(var i = 0;i < aDiv.length;i ++){
arr.push(aDiv[i]);
}
for(var i = 0;i < aDiv.length;i ++){
arr.push(aDiv[i]);
}
console.log(arr);
arr = $.unique(arr);
console.log(arr);
//$.inArray(),类似于indexOf()找内容在数组中的位置,返回1或-1
var arr = ["a","b","c","d"];
console.log($.inArray('b',arr));
//转数组
var aDiv = $.makeArray(aDiv);
aDiv.push();
$.trim()//去掉字符串的前后空格
ajax扩展:
$.param()拼接成字符串形式的数据
//key = value & key =value
var obj = {
"name":"yangkang",
"age":"24"
};
console.log($.param(obj));//name=yangkang&age=24,data中写这种json格式的会自动帮转
var obj = [//一定是name和value的组合
{
name:"yangkang",
value:"20"
}
];
obj = $.param(obj);
console.log(obj);//yangkang=20
格式化表单数据
serialize()
serializeArray()
<form action=""> <input type="text" name="a" value="1"> <input type="text" name="b" value="2"> <input type="text" name="c" value="3"> </form>
var result1 = $('form').serialize();//只是针对form中的name和value的组合
console.log(result1);//a=1&b=2&c=3
var result2 = $('form').serializeArray();
console.log(result2);//[{name:"a",value:"1"},{name:"b",value:"2"}...]
// data.html
// <span>span1</span>
// <span class="box">span2</span>
// <span>span3</span>
//div中会有1个带.box的数据
$('#div1').load("data.html .box",function(){
});
//动态加载JS,实现按需加载,例如点击一个按钮的时候加载js实现一些功能,适合性能优化,服务器环境下使用
$.getScript('data.js',function(){ ... });
$.getJSON('data.php',function(data){
console.log(data);
});
<?php
echo '{"name":"yangkang"}';
?>
//JSONP解决跨域:动态创建script标签通过src...
$.getJSON('data.php?callback=?',function(data){
console.log(data);
}).error(function(){});//返回非json格式的会走error
<?php
echo $_GET['callback'].'({"name":"yangkang"})';
?>
//全局设置
$.ajaxSetup({
type: 'post'
});
全局事件,加到document上
$.ajaxStart()
$.ajaxStop()
$.ajaxSuccess()
$.ajaxError()
$.ajaxComplete()
$.ajaxSend()
$冲突:
var J = $.noConflict();
接下来J 就可以代替 $ 啦
$.each():
可以针对原生JS数组和JSON
var arr = ['a','b','c'];
var obj = {"name":"yangkang","age":"22"};
$.each(arr,function(i,val){
console.log(i);
console.log(val);
});
$.each(obj,function(i,val){
console.log(i);
console.log(val);
});
end():
$("div").next().css('background','red').end().css('color','blue');
addBack(),后退添加链式操作:
$("div").next().css('background','red').addBack().css('color','blue');//当前和后退元素都生效
add()添加到集合:
$('div').add('span').css(...);相当于 $('div,span').css(...);
队列:
jQ中的队列存储的都是一些函数
queue() 入队
dequeue() 出队
//jQ的队列,当进行出对操作的时候,会自动执行相应的函数,一般针对运动操作
$(function(){
function a(){
alert(1);
}
function b(){
alert(2);
}
function c(){
alert(3);
}
//工具式的写法
$.queue( document,'miaov',a );
$.queue( document,'miaov',b );
$.queue( document,'miaov',c );
$.dequeue(document,'miaov');//a
$.dequeue(document,'miaov');//b
$.dequeue(document,'miaov');//c
//对象式的写法
$(document).queue('miaov',a);
$(document).queue('miaov',b);
$(document).queue('miaov',c);
$(document).dequeue('miaov',a);//a
$(document).dequeue('miaov',b);//b
$(document).dequeue('miaov',c);//c
});
$(function(){
function a(){
$('div').css('backgroundColor','red');
$('div').dequeue('fx');//a要出队,不然后续无法执行,相当于买完票不动了...
}
$('div').animate({'width':200});//先
$('div').queue('fx',a);//执行并入队,fx是固定的运动的名字
$('div').animate({'height':200});//再
$('div').animate({'left':200});//后
//[A,B,C]>>>>A>>B>>C>>>队列的操作
});
delay()的实现:
$('div').delay(2000);
$('div').queue('fx',function(){//入队
setTimeout(function(){
$('div').dequeue();//两秒后出队
},2000);
});
$.Callbacks():
function a(){
alert(1);
}
function b(){
alert(2);
}
function c(){
alert(3);
}
var cb = $.Callbacks();
cb.add(a);//添加到集合
cb.add(b);//添加到集合
cb.fire();//触发,弹出结果1和2
cb.add(c);//添加到集合
cb.remove(a);//删除a
cb.fire();//触发,弹出结果2和3
应用场景:主要源码中使用
四大参数:
$.Callbacks('once');//只触发一次fire(),第一次触发的执行
$.Callbacks('memory');//写在fire()后的add(函数)也可以触发
$.Callbacks('unique');//去除重复的函数,例如cb.add(a);cb.add(a);
$.Callbacks('stopOnFalse');//碰到add()函数中的return false,后续的所有add()都不会执行
解决定时器异步形成的问题:
var cb = $.Callbacks();
setTimeout(function(){//异步的不影响后续代码
alert(1);
cb.fire();//触发
},1000);
cb.add(function(){
alert(2);
});
基于$.Callbacks()开发的$.Deferred():
var dfd = $.Deferred();
setTimeout(function(){//异步的不影响后续代码
alert(1);
dfd.resolve();//解决对应done
dfd.reject();//未解决对应fail
},1000);
dfd.done(function(){
alert(2);
});
dfd.fail(function(){
alert(3);
});
$.ajax('aaa.php').done(function(){ ... }).fail(function(){ ... });
//第一次延迟2s,第二次立即触发的两种实现方法
var bBtn = true;
$('input').click(function(){
if(oBtn){
bBtn = false;
setTimeout(a,2000);
}
else{
a();
}
});
function a(){
alert(1);
}
var dfd = $.Deferred();
$('input').click(function(){
setTimeout(function(){
dfd.resolve();//2秒后才解决触发,第二次点的时候已经是解决状态了所以dfd.done(a)会立即触发,状态会保持住
},2000)
dfd.done(a);//第一次点击只是一个添加
});
function a(){
alert(1);
}
//两个请求同时成功之后走done()
$.when( $.ajax('aaa.php'),$.ajax('bbb.php') ).done(function(){ ... });
jQuery源码架构...:
$("div").css("backgroundColor","red"); function $(selector){ return new Jquery(selector); } function Jquery(selector){ selector > 获取元素 } Jquery.prototype.css = function(){ }
$.extend():除了复制对象的功能外还能扩展工具形式的插件
$.extend({
leftTrim:function(str){
//this == $
return str.replace(/^\s+/g,'');
}
});
var str = " hello ";
alert('('+$.leftTrim(str)+')');//工具的方式$.leftTrim()
$.fn.extend():
$.fn.extend({
size2:function(){
//this == $('div')
return this.length;
}
});
alert( $('div').size2() );//选中元素的形式
简单选项卡插件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #tab div{ width: 200px; height: 200px; border: 1px solid black; display: none; } .active{ background-color: red; } </style> <script src="jquery-1.11.1.js"></script> <script> $(function(){ //$("#tab").tabs(); $("#tab").tabs({ heads : ['体育','新闻','节能','服务'], bodys : ['体育1111','新闻11111','节能11111','服务1111'], events : 'mouseover' }); $("#tab").on('beforeChange',function(){//切换前 alert( $('#tab').find('div:visible').html() ); }); $("#tab").on('afterChange',function(){//切换后 alert( $('#tab').find('div:visible').html() ); }); }); (function($){ var defaults = { heads : ['1','2','3'], bodys : ['111111','222222','3333333'], events : 'click' }; var settings = {}; var $parent = null; function fnTab(options){ $parent = this; settings = $.extend(settings,defaults,options); create(); bind(); } function create(){ for(var i = 0;i < settings.heads.length;i ++){ var $input = $('<input type="button" value="'+ settings.heads[i] +'">'); if(i == 0){ $input.attr("class","active"); } $parent.append( $input ); } for(var i = 0;i < settings.bodys.length;i ++){ var $div = $('<div>'+ settings.bodys[i] +'</div>'); if(i == 0){ $div.show(); } $parent.append( $div ); } } function bind(){ $parent.find('input').on(settings.events,function(){ $parent.trigger('beforeChange');//前 $parent.find('input').attr('class',''); $(this).attr('class','active'); $parent.find('div').eq( $(this).index() ).show().siblings('div').hide(); $parent.trigger('afterChange');//后 }); } $.fn.extend({ tabs: fnTab }); })(jQuery); </script> </head> <body> <div id="tab"> <!-- <input class="active" type="button" value="1"> <input type="button" value="2"> <input type="button" value="3"> <div style="display:block;">11111</div> <div>22222</div> <div>33333</div> --> </div> </body> </html>
Sizzle选择器:
通用选择:
$("#div1").find("*")
层级选择:
>子
+后一个兄弟
~后所有兄弟
:animated选择有运动的元素
$("div:eq(1)")
:even
:odd
:first $("div:first")或$("div").first()
:last
:gt()
:lt() $("div:lt(2)")选择索引小于2的元素
内容筛选:
$("div:contains(aaa)")
$("div:empty")选择内容是空的元素
$("div:parent")选择有内容的元素
可见性筛选:
:hidden
:visible
子元素筛选:
:first-child $("#div1 span:first-child") #div1中所有子元素中第一个span的标签
:last-child
:first-of-type $("#div1 span:first-of-type") #div1中span中的第一个
:last-of-type
:nth-child()
:nth-of-type()
:only-child 仅有一个子元素时
:only-of-type 仅有指定类型的一个时
表单筛选:
:button
:checkbox
:radio
:checked
:disabled
:enabled
:selected
筛选方法:
filter()
not()
$("div").has(".box") 找div中有.box的子元素 作用于$("div")
$("div").find(".box") 作用于.box
jQ中的调试:FireQuery
自动注入jquery库
查看当前jQuery库版本
高亮对应选择DOM元素
数据缓存查看:$("div").data('name','hello')
模板引擎:基于jQ的Jsviews模板
http://www.jsviews.com/
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="js/jquery.js"></script> <script src="js/jsviews.min.js"></script> <script> // $.ajax({ // url:'xxx.php', // dataType:'json', // success:function(data){ // for(var attr in data){ // var $li = $('<li>'); // $li.html(data[attr].text); // $ul.append($li); // } // } // }); $(function(){ var data = { title : "排行榜", list : [ { text:'aaaaa' }, { text:'bbbbb' }, { text:'ccccc' } ] }; var $div = $("#div1"); // $.each(data,function(key,val){ // if(key == 'title'){ // var $h1 = $('<h1>'); // $h1.html( val ); // $div.append( $h1 ); // } // if(key == 'list'){ // var $ul = $('<ul>'); // for(var i = 0;i<val.length;i++){ // var $li = $('<li>'); // $li.html( val[i].text ); // $ul.append($li); // } // $div.append($ul); // } // }); var template = $.templates("#temID"); var htmlOutput = template.render(data); $div.html(htmlOutput); }); </script> <script id="temID" type="text/x-jsrender"> <h1>{{:title}}</h1> <ul> {{for list}} <li>{{:text}}</li> {{/for}} </ul> </script> </head> <body> <div id="div1"> <!-- <h1>排行榜</h1> <ul> <li>aaaaaaaaa</li> <li>bbbbbbbbb</li> <li>ccccccccc</li> </ul> --> </div> </body> </html>
单元测试Qunit:
...
jQueryMobile:
...