1. 程式人生 > >JQ筆記-加強版

JQ筆記-加強版

名詞 lte 判斷 性能 on() 好處 表示 實用 ttr

Query初級 一、介紹、基本寫法 什麽是JQ:
一個優秀的JS庫,大型開發必備

JQ的好處:

簡化JS的復雜操作
不再需要關心兼容性
提供大量實用方法

如何學習JQ:

www.jquery.com
JQ只是輔助工具,要正確面對
需要分階段學習

JQ設計思想:

選擇網頁元素
模擬CSS選擇元素
獨有表達式選擇
多種篩選方法

JQ寫法 :

方法函數化

$(function(){

//var oDiv = $(‘#div1‘); $(‘#div1‘).click(function(){
alert( $(this).html() );

});

});

鏈式操作:

$(function(){

/*var oDiv = $(‘#div1‘); oDiv.html(‘hello‘); oDiv.css(‘background‘,‘red‘); oDiv.click(function(){
alert(123);
});*/ $(‘#div1‘).html(‘hello‘).css(‘background‘,‘red‘).click(function(){
alert(123);
});

});

取值賦值合體:

$(‘#div1‘).html(‘hello‘); //賦值

//alert( $(‘#div1‘).html() ); //取值

//alert( $(‘li‘).html() ); //當一組元素的時候,取值是一組中的第一個

$(‘li‘).html(‘hello‘); //當一組元素的時候,賦值是一組中的所有元素

JQ與JS關系 :

可以共存,不能混用

$(function(){

$(‘#div1‘).click(function(){
alert( $(this).html() ); //jq的寫法
alert( this.innerHTML ); //js的寫法
alert( $(this).innerHTML ); //錯誤的
alert( this.html() ); //錯誤的
});

});



二、方法
$()下的常用方法 has() not() filter() next() prev() find() eq() index() attr() addClass() removeClass()
width() innerWidth() outerWidth() insertBefore() before() insertAfter() after() appendTo() append() prependTo() prepend() remove() on() off() scrollTop() ev pageX which preventDefault stopPropagation one() offset() position() offsetParent() val() size() each() hover() show() hide() fadeIn() fadeOut() fadeTo() slideDown() slideUp() 1、fiter() not() has() filter() : 過濾,選擇某項 not(): filter的反義詞,不選擇某項,除了某項 $(function(){ //$(‘div‘).filter(‘.box‘).css(‘background‘,‘red‘); $(‘div‘).not(‘.box‘).css(‘background‘,‘red‘); }); filter和not是針對當前元素 has是針對當前元素的子元素 has() : 包含 $(function(){ $(‘div‘).has(‘span‘).css(‘background‘,‘red‘);//div中包含span的元素 $(‘div‘).filter(‘.box‘).css(‘background‘,‘red‘); //div中class為box的元素 }); 2、next() 、prev()、find() next()是找下一個兄弟節點,參數具有篩選功能 prev()是找上一個兄弟節點,參數具有篩選功能 find()是選擇子元素中的 $(‘div‘).find(‘h2‘).eq(1).css(‘background‘,‘red‘); 3、 eq() idnex() eq(): 代表一組元素的下標,從0開始。 index(): $(function(){ alert( $(‘#h‘).index() ); //索引就是當前元素在所有兄弟節點中的位置,從0開始 }); 4、addClass()、removeClass(): $(function(){ $(‘div‘).addClass(‘box2 box4‘); $(‘div‘).removeClass(‘box1‘); }); 5、width()、innerWidth()、outerWidth() div{ width:100px; height:100px; background:red; padding:10px; border:10px #000 solid; margin:10px;} $(function(){ alert( $(‘div‘).width() ); //width alert( $(‘div‘).innerWidth() ); //width + padding alert( $(‘div‘).outerWidth() ); //width + padding + border alert( $(‘div‘).outerWidth(true) ); //width + padding + border + margin }); 6、insertBefore()、before()、insertAfter()、after(): $(‘span‘).insertBefore( $(‘div‘) ); // 動詞、把span添加到div前面 $(‘div‘).before( $(‘span‘) ); //名詞、div的前面是span $(‘div‘).insertAfter( $(‘span‘) ); // 動詞、把div添加到span後面 $(‘span‘).after( $(‘div‘) ); //名詞、 span的後面是div 7、appendTo()、prependTo()、append() 、prepend() $(‘div‘).appendTo( $(‘span‘) ); //把div追加到span中的元素的最後 $(‘span‘).append( $(‘div‘) ); //span中最後面添加的是div $(‘div‘).prependTo( $(‘span‘) ); //把div放在span中的元素的最前面 $(‘span‘).prepend( $(‘div‘) ); //span中最前面添加的是div 8、創建節點 var $iLi = $("<li>香蕉</li>"); $(‘ul‘).append($iLi); 9、刪除節點:remove()、detach()、empty() remove():刪除節點,返回的是刪除的節點,刪除完成後,與該節點綁定的事件也都刪除 $(function(){ //刪除之後,再次點擊無反應 $(‘div‘).click(function(){ alert(123); }); var oDiv = $(‘div‘).remove(); $(‘body‘).append( oDiv ); }); detach() : 跟remove方法一樣,只不過會保留刪除這個元素的事件操作行為 $(function(){ $(‘div‘).click(function(){ alert(123); }); var oDiv = $(‘div‘).detach(); $(‘body‘).append( oDiv ); }); 三、 1、事件寫法: $(‘div‘).click(function(){ alert(123); }); $(‘div‘).on(‘click‘,function(){ alert(123); }); $(‘div‘).on(‘click mouseover‘,function(){ alert(123); }); $(‘div‘).on({ ‘click‘ : function(){ alert(123); }, ‘mouseover‘ : function(){ alert(456); } }); 觸發一次取消該事件: $(‘div‘).on(‘mouseover‘,function(){ alert(123); $(‘div‘).off(‘mouseover‘); }); 2、scrollTop():滾動距離 $(function(){ $(document).click(function(){ alert( $(window).scrollTop() ); //滾動距離 }); }); 3、事件相關細節:無兼容問題、ev、ev.pageX、ev.which、one()、阻止默認事件和阻止冒泡 $(‘div‘).click(function(ev){ //ev : event對象 //ev.pageX(相對於文檔的) = clientX(相對於可視區)+ scrollTop(滾動距離) //ev.which = keyCode ev.preventDefault(); //阻止默認事件 ev.stopPropagation(); //阻止冒泡的操作 return false; //阻止默認事件 + 阻止冒泡的操作 }); one(): $(‘div‘).one(‘click‘,function(){ //只執行事件一次 alert(123); }); 4、位置操作:offset()、position() <div id=‘div1‘> <div id=‘div2‘></div> </div> #div1{ width:200px; height:200px; background:red; overflow:hidden; margin:20px; position:absolute;} #div2{ width:100px; height:100px; background:yellow; margin:30px; position:absolute; left:25px;} $(function(){ //div2.offsetLeft; //js原生offset距離是指到定位父級的距離,沒有定位父級就是到文檔的距離 //alert( $(‘#div2‘).offset().left ); //獲取到文檔屏幕的左距離 alert( $(‘#div2‘).position().left ); //父級有定位,到有定位的父級的left值,把當前元素轉化成類似定位的形式。若父級沒有定位,則返回父級元素的margin-left值。 });

5、parent()、offsetParent()

parent() : 獲取父級
offsetParent() : 獲取有定位的父級 6、val()、size()、each() $(function(){
alert( $(‘input‘).val() ); //獲取value值 $(‘input‘).val(456); //修改value值 alert( $(‘li‘).size() ); //獲取元素的個數,像length $(‘li‘).each(function(i,elem){ //遍歷。一參:下標 ;二參 : 每個元素
$(elem).html(i);
}); }); 7、hover() hide() show() fadeIn() fadeOut() fadeTo() slideUp() slideDown() $(function(){ $(‘#div1‘).hover(function(){ //參數為兩個函數,鼠標移入和移出
//$(‘#div2‘).hide(3000); //隱藏,參數為毫秒,默認400 //$(‘#div2‘).fadeOut(1000); //淡出,變透明 //$(‘#div2‘).slideUp();//由下向上縮短隱藏 $(‘#div2‘).fadeTo(1000,0.5);// 兩個參數分別為時間和不透明度
},function(){
//$(this).css(‘background‘,‘red‘); //$(‘#div2‘).show(3000);//顯示 //$(‘#div2‘).fadeIn(1000);//淡入,變不透明 //$(‘#div2‘).slideDown();//由上向下延伸顯示 $(‘#div2‘).fadeTo(1000,1);// 兩個參數分別為時間和不透明度
}); });
JQuery 高級 一、基礎方法 基礎方法擴充 $()下的常用方法: $().next() get() : 下標和length屬性 outerWidth() : 針對隱藏元素和參數true text() : 合體的特例 remove() : detach() $() : $(document).ready() parents() closest() siblings() nextAll() prevAll() parentsUntil() nextUntil() prevUntil() clone() wrap() wrapAll() wrapInner() unwrap() add() slice() serialize() serializeArray() animate() stop() delay() delegate() undelegate() trigger() ev.data ev.target ev.type 1、get() get() : 就是把JQ轉成原生JS,不帶參數表示集合,參數為索引值,帶參數表示哪一個 $(function(){ alert( $(‘#div1‘).get(0).innerHTML );
for(var i=0;i<$(‘li‘).length;i++){ //jquery本身有length屬性
$(‘li‘).get(i).style.background = ‘red‘;
//$(‘li‘)[i].style.background = ‘red‘;// [i]和get()方法一樣
} }); 2、outerWidth()與原生的區別 outerWidth():包括width和innerWidth都能獲取隱藏元素 offsetWidth : 是獲取不到隱藏元素的值 $(function(){ alert( $(‘#div1‘).get(0).offsetWidth ); alert( $(‘#div1‘).outerWidth() ); }); 3、text() 和 html() 的區別 $(function(){ alert( $(‘div‘).html() );//只獲取一組元素第一個 $(‘div‘).html(‘文本‘); //可以修改文本內容,修改的是所有的元素標簽 $(‘div‘).html(‘<li>lilili</li>‘);//可以修改標簽, 修改是修改所有元素的標簽 alert( $(‘div‘).text() ); //會獲取所有的內容(特例) $(‘div‘).text(‘<h3>h3</h3>‘); //不能修改標簽,只能修改集合中所有文本內容 }); 4、parents()、closest() parents() : 獲取當前元素的所有祖先節點,參數就是篩選功能 closest() : 獲取最近的指定的祖先節點(包括當前元素自身),必須要寫篩選的參數,只能找到一個元素 $(function(){ //$(‘#div2‘).parents(‘.box‘).css(‘background‘,‘red‘);//所有class為box的元素都變紅 $(‘#div2‘).closest(‘.box‘).css(‘background‘,‘red‘); //最近的一個class為box的祖先節點,也包括自己。 }); 5、siblings()、nextAll() 、prevAll()、parentsUntil()、nextUntil()、prevUntil() siblings() : 找所有的兄弟節點,參數也是篩選功能 nextAll() : 下面所有的兄弟節點,參數也是篩選功能 prevAll() : 上面所有的兄弟節點 parentsUntil(): 截止到哪一個祖先節點,不包括截止的那一個 nextUntil(): 截止到哪一個下面的兄弟節點,不包括截止的那一個 prevUntil(): 截止到哪一個上面的兄弟節點,不包括截止的那一個 $(function(){ $(‘span‘).nextUntil(‘h2‘).css(‘background‘,‘red‘); //不包括h2 }); 6、clone() $(function(){ //$(‘div‘).appendTo( $(‘span‘) ); //$(‘span‘).get(0).appendChild( $(‘div‘).get(0) ); //clone() : 不帶參數時,只復制節點不復制它的事件;接收一個參數true ,作用可以復制之前的事件操作行為 $(‘div‘).click(function(){ alert(123); }); $(‘div‘).clone(true).appendTo( $(‘span‘) ); }); 7、wrap() 、wrapAll() 、wrapInner()、unwrap() //wrap() : 包裝 ,對指定的一組元素單個單個的包裝 //wrapAll() : 整體包裝,把指定的一組元素整體包裝 //wrapInner() : 內部包裝,在指定元素內部進行包裝 //unwrap() : 刪除包裝 ( 刪除父級 : 不包括body ) $(function(){ //$(‘span‘).wrapInner(‘<div>‘); // 參數一定要加標簽符號 $(‘span‘).unwrap(); }); 8、add() 增加元素 $(function(){ var elem = $(‘div‘); var elem2 = elem.add(‘span‘); elem.css(‘color‘,‘red‘); elem2.css(‘background‘,‘yellow‘); }); 9、slice() 截取元素 $(function(){ $(‘li‘).slice(1,4).css(‘background‘,‘red‘); //截取第二個到第四個 [1,4) }); 10、數據串聯化: serialize()、serializeArray() <form> <input type="text" name="a" value="1"> <input type="text" name="b" value="2"> <input type="text" name="c" value="3"> </form> $(function(){ console.log($(‘form‘).serialize()); //string類型 : a=1&b=2&c=3 console.log( $(‘form‘).serializeArray() ); /*
JSON類型: [ { name : ‘a‘ , value : ‘1‘ }, { name : ‘b‘ , value : ‘2‘ }, { name : ‘c‘ , value : ‘3‘ } ]
*/ }); 11、animate() : 第一個參數 : {} 運動的值和屬性 第二個參數 : 時間(運動快慢的) 默認 : 400 第三個參數 : 運動形式 只有兩種運動形式 ( 默認 : swing(慢快慢) 、linear(勻速) ) 第四個參數 : 回調函數 $(function(){ $(‘#div1‘).click(function(){ $(this).animate({width : 300 , height : 300} , 4000 , ‘linear‘,function(){ alert(123); }); $(‘#div2‘).animate({width : 300 , height : 300} , 4000 , ‘swing‘); }); }); 12、stop()、finish()、delay() $(function(){ $(‘#div1‘).click(function(){ //回調函數可以改寫成鏈式操作 $(this).animate({width : 300} , 2000 , ‘linear‘,function(){ $(this).animate({height : 300}); }); $(this).animate({width : 300} , 2000).animate({height : 300} , 2000); // delay() : 延遲執行 delay(1000): 延遲1秒後執行後續操作 $(this).animate({width : 300} , 2000).delay(1000).animate({height : 300} , 2000); }); $(‘#div2‘).click(function(){ //$(‘#div1‘).stop(); //默認 : 只會阻止當前運動 //$(‘#div1‘).stop(true); //阻止當前和後續的運動 //$(‘#div1‘).stop(true,true); //可以立即停止到當前運動指定的目標點 $(‘#div1‘).finish(); //立即停止到所有(當前和後續操作)指定的目標點 }); }); 13、事件委托:delegate()、undelegate() $(function(){ //這種做法還要遍歷每個li,影響性能 $(‘li‘).on(‘click‘,function(){ this.style.background = ‘red‘; }); //事件委托:利用事件冒泡,好處:提高性能、後續動態添加的元素也有事件操作 $(‘ul‘).delegate(‘li‘,‘click‘,function(){ // 第一個參數是事件實際觸發的對象 this.style.background = ‘red‘; // $(‘ul‘).undelegate(); 取消事件委托 }); }); 14、主動觸發:trigger() $(function(){ $(‘#div1‘).on(‘click‘,function(){ alert(123); }); $(‘#div1‘).trigger(‘click‘); //主動觸發 click事件 $(‘#div1‘).on(‘show‘,function(){ alert(123); }); $(‘#div1‘).on(‘show‘,function(){ alert(456); }); $(‘#div1‘).trigger(‘show‘); //主動觸發 自定義show所有事件的操作 }); 15、事件的細節:ev.data 、ev.target 、ev.type $(function(){ $(‘#div1‘).on(‘click‘,{name:‘hello‘},function(ev){ alert(ev.data.name); // 事件中數據:hello alert( ev.target ); // 事件操作的對象:div alert( ev.type ); //事件操作類型 :click }); });
二、工具方法 $下的常用方法:不是$() type() trim() inArray() proxy() noConflict() parseJSON() makeArray() ajax() : json形式的配置參數 url success error contentType data type dataType cache timeout 抽象出來的方法: get() post() getJSON() 支持jsonp的形式:指定?callback=? 插件: $ $.extend $.fn $.fn.extend 深入: $.Callbacks() : 回調對象 deferred() : 延遲對象 $.hodeReady() : 持有和釋放ready $.dequeue() : 執行隊列 $.support : 功能檢測 16、$、$.type //$().css() $().html() $().val() : 只能給JQ對象用 //$.xxx() $.yyy() $.zzz() : 不僅可以給JQ用,也可以給原生JS用 : 叫做工具方法 $(function(){
//var a = null; //$.type() : 也是判斷類型 alert( typeof a ); // js原生 alert( $.type(a) ); // 比原生的類型細分的深
}); 17、$.trim() $(function(){
var str = ‘ hello ‘; alert(‘(‘+$.trim(str)+‘)‘); // 去掉hello前後的空格 (hello)
}); 18、$.inArray() //inArray() : 類似於 indexOf $(function(){ var arr = [‘a‘,‘b‘,‘c‘,‘d‘]; alert( $.inArray(‘b‘,arr) ); // 返回數組中的索引,沒有找到返回 -1 ,相當於indexOf }); 19、$.proxy() $(function(){
//proxy() : 改變this指向的 function show(n1,n2){
alert(n1);
alert(n2);
alert(this);
} //show(); $.proxy(show , document)(3,4); // 在後面的括號中傳參,立即執行 $.proxy(show , document,3,4)( ); //也可在$.proxy()中傳參 $(document).click( $.proxy(show,window,3,4) ); //在$.proxy()中傳參,若在後面添加一個()並在括號裏傳參,頁面刷新後立即執行
}); 20、$.noConflict() 防止jQuery中 $ 沖突的 var mao = $.noConflict(); //把mao改成 jQuery 中 $ 的作用 var $ = 10; //僅僅是一個變量 mao(function(){ mao(‘body‘).css(‘background‘,‘red‘); }); 21、$.parseJSON() 將字符串類型轉成json類型 var str = ‘{"name":"hello"}‘; console.log($.parseJSON( str ).name); //hello 22、$.makeArray() 將類數組轉化成數組,可以具備數組的方法 var aDiv = document.getElementsByTagName(‘div‘); //類數組 $.makeArray(aDiv).push(1); 23、ajax() !看文檔!!! $.ajax({
url : ‘xxx.php‘, data : ‘name=hello&age=20‘, type : ‘POST‘, success : function(data){
alert(1);
}, error : function(){
alert(2);
}
}); $.get(‘xxx.php‘,function(){ }); $.post(‘xxx.php‘,function(){ }); $.getJSON(‘xxx.php?callback=?‘,function(data){ data .. }); 隨機({}); ········ 24、擴展插件:$.extend、$.fn.extend <script src="jquery-1.10.1.min.js"></script> <script>
//$.extend : 擴展工具方法下的插件形式 $.xxx() $.yyy() //$.fn.extend : 擴展到JQ對象下的插件形式 $().xxx() $().yyy() //寫成JSON形式: $.extend({
leftTrim : function(str){
return str.replace(/^\s+/,‘‘);
},
rightTrim : function(){},
aaa : function(){
alert(1);
},
bbb : function(){}
}); $.fn.extend({
drag : function(){
//this : $(‘#div1‘)
var disX = 0;
var disY = 0;
var This = this;
this.mousedown(function(ev){
disX = ev.pageX - $(this).offset().left;
disY = ev.pageY - $(this).offset().top;
$(document).mousemove(function(ev){
This.css(‘left‘ , ev.pageX - disX);
This.css(‘top‘ , ev.pageY - disY);
});
$(document).mouseup(function(){
$(this).off();
});
return false;
});
},
aaa : function(){
alert(2);
}
});
</script> <script>
//$.trim() //$.leftTrim() var str = ‘ hello ‘; alert( ‘(‘+$.leftTrim(str)+‘)‘ ); // 只清除了左空格 $(function(){ $(‘#div1‘).drag(); //拖拽 }); $.aaa(); // 1 $().aaa(); //2
</script> <div id="div1"></div>

JQ筆記-加強版