jquery基本操作笔记
jq和js
可以共存,不能混用;
$('.box').css('background','red'); $(".box").css({ color: "#ff0011", background: "blue"}); $('li:eq(2)').css('background','red'); //:first選擇 $('li:odd').css('background','red'); //even奇數(shù)行,odd偶數(shù)行 $('li').filter('.box').css('background','red'); filter過濾、篩選; $('li').filter('[title=hello]').css('background','red');方法函數(shù)化:
window.onload = function(){}; $(function(){}); function $(){} innerHTML = 123; html(123) function html(){} onclick = function(){}; click(function(){}) function click(){} $('#div1').click(function(){alert( $(this).html() ); });jquery中的this的寫法是?? $(this)? ;html()? 因為方法函數(shù)法的思想的存在,() 是不能省去的,運行函數(shù);這在jquery中很常見;
js和jquery的關(guān)系:
可以互存,不能混用;
$(function(){$('#div1').click(function(){//alert( $(this).html() ); //jq的寫法;//alert( this.innerHTML ); //js的寫法;這樣寫也是正確的;alert( $(this).innerHTML ); //錯誤的;前面是jquery,后面是js,混用了,不允許;alert( this.html() ); //錯誤的;前面是js,后面是jquery,混用了,不允許;}); });鏈式操作:
$(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);}); });建議熟悉了,再寫鏈式寫法;
取值和賦值合體:
賦值和取值用的同一種方法,只不過是通過有沒有參數(shù)來決定是取值還是賦值;
$(function(){//oDiv.innerHTML = 'hello'; //賦值//alert( oDiv.innerHTML ); //取值//$('#div1').html('hello'); //賦值//alert( $('#div1').html() ); //取值css('width','200px') //設(shè)置width是200px;css('width') //獲取width的值; });取值和賦值:獲取的時候只能獲取一個,賦值的時候賦值到所有的;
$(function(){//alert( $('li').html() ); //當一組元素的時候,取值是一組中的第一個;會彈出內(nèi)容:aaa$('li').html('hello'); //當一組元素的時候,賦值是一組中的所有元素 });$()下的常用方法
attr()
$(function(){//alert($('div').attr('title')); 獲取title屬性$('div').attr('title','456'); //設(shè)置title$('div').attr('class','box'); //設(shè)置class });filter:過濾
not: filter的反義詞
$(function(){//$('div').filter('.box').css('background','red'); //只帶有box的才會被選擇$('div').not('.box').css('background','red'); //不帶有box的才會選擇;not和filter是反義詞 });has和filter的區(qū)別
has是包含的意思,選擇的是元素里面的東西;
而filter針對的元素自身的選擇;
$(function(){//$('div').has('span').css('background','red');//$('div').has('.box').css('background','red'); //has是選擇元素里面的東西,不能選擇到第二個div$('div').filter('.box').css('background','red'); //filter是針對元素自身的;只會選擇到第二個div });next和prev:
next選擇下一個兄弟節(jié)點;
prex選擇上一個兄弟節(jié)點;
find??? 查找當前元素下所有的后代元素;
eq()??? 一組中的第幾個;
index()? 一組元素的索引;通過一組索引,來控制另外一個索引;
$(function(){alert( $('#h').index() ); //索引就是當前元素在所有兄弟節(jié)點中的位置; });選項卡:
原生js和jquery:
window.onload = function(){var oDiv = document.getElementById('div1');var aInput = oDiv.getElementsByTagName('input');var aCon = oDiv.getElementsByTagName('div');for(var i=0;i<aInput.length;i++){aInput[i].index = i;aInput[i].onclick = function(){for(var i=0;i<aInput.length;i++){aInput[i].className = '';aCon[i].style.display = 'none';}this.className = 'active';aCon[this.index].style.display = 'block';};} };$(function(){
????$('#div1').find('input').click(function(){
????????$('#div1').find('input').attr('class','');
????????$('#div1').find('div').css('display','none');
????????$(this).attr('class','active');
????????$('#div1').find('div').eq(?$(this).index()?).css('display','block');
????});
});
<body> <div id="div1"><input class="active" type="button" value="1" /><input type="button" value="2" /><input type="button" value="3" /><div style="display:block">111111</div><div>222222</div><div>333333</div> </div> </body>這里的jquery是根據(jù)js的思路來編寫的;
也可以用其他的思路來做這個選項卡,用到siblings()等;
addClass和removeClass
$(function(){$('div').addClass('box2 box4');$('div').removeClass('box1'); });width()?? innerWidth()?? outerWidth()? 獲取元素的寬和區(qū)別:
$(function(){alert( $('div').width() ); //widthalert( $('div').innerWidth() ); //width + paddingalert( $('div').outerWidth() ); //width + padding + borderalert( $('div').outerWidth(true) ); //width + padding + border + margin });insertBefore() ?insertAfter()??
注意:insertBefore是剪切的功能,不是復(fù)制的功能;
$(function(){//$('span').insertBefore( $('div') ); //將span調(diào)整到div的前面,jq中的insertBefore和js中的insertBefore是一樣的;具備剪切的功能,而不是復(fù)制的功能;//$('div').insertAfter( $('span') ); //將div放在span的后面;//$('div').appendTo( $('span') ); //和js中的appendChildren是一樣的;作用是把一個節(jié)點添加到指定節(jié)點最后的位置;//$('div').prependTo( $('span') ); //原生js中沒有,作用是把一個節(jié)點添加到指定節(jié)點最開始的位置; //insertBefore和before的區(qū)別 :后續(xù)操作變了;主要是我們寫鏈式操作會有影響;//$('span').insertBefore( $('div') ).css('background','red');$('div').before( $('span') ).css('background','red'); });remove()? 刪除節(jié)點
$(function(){$('div').remove(); });on()? off()?? 事件的寫法:
off取消事件;
$(function(){/*$('div').click(function(){alert(123);});*//*$('div').on('click',function(){ //支持多個事件,支持系統(tǒng)事件和自定義事件alert(123); });*//*$('div').on('click mouseover',function(){ //多個事件,中間用空格alert(123);});*//*$('div').on({'click' : function(){ //中間用冒號alert(123);},'mouseover' : function(){alert(456);}});*/ //點擊彈出123.移入彈出456 說明on還是很靈活的$('div').on('click mouseover',function(){alert(123);$('div').off('mouseover'); //執(zhí)行后,mouseover事件會被關(guān)閉}); });scrollTop()?? 獲取和設(shè)置滾動距離
$(function(){$(document).click(function(){alert( $(window).scrollTop() ); //獲取滾動距離}); });編寫彈窗效果:
首先,在DOM中創(chuàng)建元素是非常容易的事情;
var oDiv = $('<div>div</div>'); //創(chuàng)建div元素和內(nèi)容 $('body').append( oDiv );彈窗效果:
$(function(){$('#input1').click(function(){//動態(tài)創(chuàng)建元素和內(nèi)容var oLogin = $('<div id="login"><p>用戶名:<input type="text" /></p><p>密碼:<input type="text" /></p><div id="close">X</div></div>'); //中間不能有空格$('body').append( oLogin ); //插入元素//讓彈窗居中oLogin.css('left' , ($(window).width() - oLogin.outerWidth())/2 ); //設(shè)置left值oLogin.css('top' , ($(window).height() - oLogin.outerHeight())/2 ); //設(shè)置top值$('#close').click(function(){oLogin.remove(); //移除節(jié)點});//在調(diào)整窗口大小事件和滾動事件,調(diào)整彈出窗的位置;$(window).on('resize scroll',function(){ //在調(diào)整窗口大小事件和滾動事件oLogin.css('left' , ($(window).width() - oLogin.outerWidth())/2 );oLogin.css('top' , ($(window).height() - oLogin.outerHeight())/2 + $(window).scrollTop() ); //top值要注意加上滾動距離});}); });ev? pageX? which?
preventDefault? stopPropagation
one()
$(function(){/*$('div').click(function(ev){//ev : jq中直接使用,是兼容后的event對象//ev.pageX(鼠標坐標-->相對于文檔的) js中是使用clientX(相對于可視區(qū)域的)//ev.which : js中的keyCodeev.preventDefault(); //阻止默認事件ev.stopPropagation(); //阻止冒泡的操作return false; //阻止默認事件 + 阻止冒泡的操作});*/$('div').one('click',function(){ //one-->只執(zhí)行事件一次alert(123);}); });offset()? position()
$(function(){//div2.offsetLeft//alert( $('#div2').offset().left ); //獲取到屏幕的左距離 offset().left offset.top()alert( $('#div2').position().left ); //到有定位的父級的left值,把當前元素轉(zhuǎn)化成類似定位的形式,注意是不算margin的 });parent() offsetParent()?? 獲取有定位的父級
parent() : 獲取父級,不管父級是否有定位; 注意這里沒有加s,不是parents,jq中還有parents()方法,見下
offsetParent() : 獲取有定位的父級
$(function(){//parent() : 獲取父級//offsetParent() : 獲取有定位的父級//$('#div2').parent().css('background','blue');$('#div2').offsetParent().css('background','blue'); });val()? 獲取元素的value值;
size() 獲取一組元素的長度;像length;
each() jq中的循環(huán);原生for循環(huán)的加強版
$(function(){//alert( $('input').val() ); 獲取value值//$('input').val(456); 賦值value值alert( $('li').size() ); //4 獲取一組元素的長度;像length$('li').each(function(i,elem){ //一參:下標 二參 : 每個元素$(elem).html(i);}); });拖拽jquery實現(xiàn):
$(function(){var disX = 0;var disY = 0;$('div').mousedown(function(ev){disX = ev.pageX - $(this).offset().left; //存儲距離disY = ev.pageY - $(this).offset().top;$(document).mousemove(function(ev){$('div').css('left',ev.pageX - disX);$('div').css('top',ev.pageY - disY);});$(document).mouseup(function(){$(document).off(); //鼠標彈起的時候取消事件});return false; //阻止默認事件和冒泡}); });hover()????? 模擬css中的hover,鼠標移入移除;
hover???????? 鼠標移入和鼠標移除結(jié)合的方法;
hover(function(){},function(){})
?
Show() hide()??????????? 接受一個參數(shù)- ->? 時間(ms)?????????????? 長,寬,透明度都要變化
fadeIn()?? fadeOut()????淡出效果和淡出效果? 改變透明度
fadeTo()??? 指定到一個范圍,有兩個參數(shù),第一個是時間,第二個是透明度值
$('#div2').fadeTo(1000,0.5);slideDown()?? slideUp()???????? 向下展開,向上卷起;
?
get()方法
$(function(){//document.getElementById('div1').innerHTML//alert( $('#div1').get(0).innerHTML ); get需要標注下標;將jquery轉(zhuǎn)成原生js/*for(var i=0;i<$('li').get().length;i++){ //這里通過get()轉(zhuǎn)成js,這里的length相對于js的$('li').get(i).style.background = 'red';}*/for(var i=0;i<$('li').length;i++){ //這里的length是JQ中的屬性,也是使用正確的;$('li').get(i).style.background = 'red';//$('li')[i].style.background = 'red'; 得到元素后,后面加一個中括號,寫成下標的形式,也就自動轉(zhuǎn)成原生js的形式了;這是一種偷巧的寫法;} });outerWidth與原生的區(qū)別:
$(function(){//alert( $('#div1').get(0).offsetWidth ); //這里原生js,如果把div1設(shè)置為隱藏,獲取的值為0;alert( $('#div1').outerWidth() ); //不管是顯示和隱藏的,都可以獲取到值; });text()?? ?會獲取所有的內(nèi)容(特例),不會獲取到標簽,而html會獲取到標簽;
$(function(){//alert( $('div').html() );//alert( $('div').text() ); //會獲取所有的內(nèi)容(特例)$('div').text('<h3>h3</h3>'); //在瀏覽器中會輸出純文本<h3>h3</h3> });remove()和detach()的區(qū)別:
//remove方法刪除元素的時候會把元素的操作行為也刪除掉;
//detach()?:?跟remove方法一樣,只不過會保留刪除這個元素的操作行為
$(function(){$('div').click(function(){alert(123);});var oDiv = $('div').detach(); //這里如果用remove(),恢復(fù)的時候,點擊行為會無效$('body').append( oDiv ); });$()?? :? $(document).ready()? 與window.οnlοad=function(){}的區(qū)別:
$(function(){ //等DOM加載完就可以執(zhí)行了 , 性能要好 }); 是 $(document).ready(function(){ }); 的簡寫;?window.onload?=?function(){};?//等圖片和flash等加載完才執(zhí)行;
//DOMContentLoaded
parents()?? closest()
//parents()?:?獲取當前元素的所有祖先節(jié)點,參數(shù)就是篩選功能
//closest()?:?獲取最近的指定的祖先節(jié)點(包括當前元素自身),必須要寫篩選的參數(shù),只能找到一個元素
$(function(){//$('#div2').parents().css('background','red'); //獲取到所有祖先節(jié)點 div1,body,html//$('#div2').parents('.box').css('background','red'); //獲取到class為box的祖先元素$('#div2').closest('.box').css('background','red'); });siblings() 獲取元素的所有兄弟節(jié)點 ;
nextAll() 獲取下面所有的兄弟節(jié)點;
preAll() 獲取上面所有的兄弟節(jié)點;
parentsUntil()?? nextUntil()?? prevUntil()
//siblings()?:?找所有的兄弟節(jié)點,參數(shù)也是篩選功能
//nextAll()?:?下面所有的兄弟節(jié)點,參數(shù)也是篩選功能
//prevAll()?:?上面所有的兄弟節(jié)點
//Until()?:?截止
$(function(){$('span').nextUntil('h2').css('background','red'); });clone()? 克隆節(jié)點:
$(function(){//$('div').appendTo( $('span') ); //剪切行為//$('span').get(0).appendChild( $('div').get(0) );//clone() : 可以接收一個參數(shù) ,作用可以復(fù)制之前的操作行為$('div').click(function(){alert(123);});$('div').clone(true).appendTo( $('span') ); //參數(shù)true作用可以復(fù)制之前的操作行為 });wrap()? wrapAll()? wrapInner()? unwrap()?? 包裝,包裝方法
在外面包裹一下
$('span').wrapInner('<div>'); //在span外包裝div
?wrapAll() 整體包裝:
//wrap()?:?包裝
//wrapAll()?:?整體包裝;?會影響結(jié)構(gòu)
//wrapInner()?:?內(nèi)部包裝;
//unwrap()?:?刪除包裝?(?刪除父級?:?不能刪除body?)
$(function(){//$('span').wrapInner('<div>'); div在span里面了$('span').unwrap(); });add()
$(function(){/*var elem = $('div');var elem2 = elem.add('span');elem.css('color','red');elem2.css('background','yellow');*/$('li').slice(1,4).css('background','red'); });slice()
$('li').slice(1,4).css('background','red');
第一個參數(shù)是起始位置,4是結(jié)束位置(選中的不包括結(jié)束位置);
serialize()??? serializeArray()?? 數(shù)據(jù)串連化
$(function(){//console.log($('form').serialize()); //string : a=1&b=2&c=3console.log( $('form').serializeArray() );[{ name : 'a' , value : '1' },{ name : 'b' , value : '2' },{ name : 'c' , value : '3' }] }); </script> </head> <body> <form><input type="text" name="a" value="1"><input type="text" name="b" value="2"><input type="text" name="c" value="3"> </form>jquery中的animate()
//animate()?:?
//第一個參數(shù)?:?{}?運動的值和屬性
//第二個參數(shù)?:?時間(運動快慢的)??默認?:?400?毫秒
//第三個參數(shù)?:?運動形式?只有兩種運動形式?(?默認?:?swing(緩沖,慢快慢)?linear(勻速)?) 默認是緩沖(慢快慢)
//第四個參數(shù)?:??回調(diào)函數(shù);運行結(jié)束后,回調(diào)函數(shù)
$(function(){$('#div1').click(function(){$(this).animate({width : 300 , height : 300} , 3000 , 'linear',function(){alert(123); //回調(diào)函數(shù),也可以用鏈式操作來寫;});$('#div2').animate({width : 300 , height : 300} , 3000 , 'swing');}); });鏈式操作來寫:先寬后高;和上述的回調(diào)函數(shù)效果一致;
$(this).animate({width : 300} , 2000).animate({height : 300} , 2000);Stop()方法:
$('#div2').click(function(){//$('#div1').stop(); //默認 : 只會阻止當前運動(當前步驟)//$('#div1').stop(true); //阻止所有后續(xù)的運動//$('#div1').stop(true,true); //立即停止到當前步驟指定的目標點,當前步驟的目標點// stop不能做到,點一下-->直接到最后的目標點-->用finish()$('#div1').finish(); //立即停止到所有指定的目標點,到最后的目標點});delay()
延遲
jquery中事件委托:
delegate()?? undelegate()
$(function(){/*$('li').on('click',function(){this.style.background = 'red';});*/$('ul').delegate('li','click',function(){ //事件委托this.style.background = 'red'; $('ul').undelegate(); //阻止事件委托}); });trigger()? 主動觸發(fā)
$(function(){/*$('#div1').on('click',function(){alert(123);});$('#div1').trigger('click'); //主動觸發(fā)*/$('#div1').on('show',function(){alert(123);});$('#div1').on('show',function(){alert(456);});$('#div1').trigger('show'); });事件細節(jié):
$(function(){$('#div1').on('click',{name:'hello'},function(ev){//alert(ev.data.name); 這里的ev.data等于{name:'hello'}這個整體,ev.data.name就是hello//alert( ev.target ); 當前操作的事件源,全兼容的alert( ev.type ); 當前操作事件類型}); });jquery的工具方法:
我們前面的都是$().css()??$().html()??$().val()??:?只能給JQ對象用;
?
而實際上,我們還存在另外一種寫法:?? 不僅可以給jquery用,也可以給原生js用;
$.xxx()? $.yyy()? $.zzz()? : 不僅可以給JQ用,也可以給原生JS用 : 叫做工具方法
type()
trim()
$(function(){//var a = null;//$.type() : 也是判斷類型,功能更加強大,能判斷出更多的類型//alert( typeof a ); 原生js的判斷變量類型//alert( $.type(a) ); 用$.type()判斷出更多類型,功能更強大var str = ' hello ';alert('('+$.trim(str)+')'); //$.trim()去除前后的空格 });inArray()?? 類似于 indexOf
proxy()? 改變this指向;
$(function(){//var arr = ['a','b','c','d'];//alert( $.inArray('b',arr) ); //b在array這個數(shù)組中的位置;若沒有會返回-1;有的話就返回位置//proxy() : 改變this指向的function show(n1,n2){alert(n1);alert(n2);alert(this);}//show();//$.proxy(show , document)(); //show的this指向document//$.proxy(show , document,3,4)(); //對于傳參,傳參可以這樣傳$.proxy(show , document,3)(4); //也可以這樣混著傳參//jquery中為什么要這樣傳參呢?//$(document).click( $.proxy(show,window)(3,4) ); //如果這樣傳參,刷新就直接調(diào)用函數(shù)$(document).click( $.proxy(show,window,3,4) ); //這樣傳參,就是在click后才會調(diào)用函數(shù),而不會直接調(diào)用; });$.noConflict()? 防止沖突
//$?,?jQuery??$=jQuery?一回事?$不是jQuery獨有的
//noConflict() : 防止沖突的 var aaa= $.noConflict(); var $ = 10; aaa(function(){aaa('body').css('background','red'); });parseJSON()? 把字符串轉(zhuǎn)換成json類型
var str = '{"name":"hello"}'; //字符串必須是嚴格的JSON格式 alert($.parseJSON( str ).name); //把字符串轉(zhuǎn)換成jsonmakeArray()?
window.onload = function(){var aDiv = document.getElementsByTagName('div'); //只是集合,不是真正的數(shù)組,我們叫做類數(shù)組(類似于數(shù)組)$.makeArray(aDiv).push(); //通過 $.makeArray(aDiv) 把 類數(shù)組 轉(zhuǎn)換成 真正的數(shù)組 };jquery中使用ajax
<script> /*$.ajax({url : 'xxx.php',data : 'name=hello&age=20',type : 'POST', //默認是getsuccess : function(data){ //請求成功以后的回調(diào)函數(shù)alert(1);},error : function(){ //請求失敗之后alert(2);} });*/ $.get('xxx.php',function(){ //ajax的get請求可用get(),第一個是地址,第二個是成功后回調(diào) }); // $.get()和$().get()是有區(qū)別的;前者是ajax的get請求方法,后者是將jQuery對象轉(zhuǎn)換成js原生對象 $.post('xxx.php',function(){ }); $.getJSON('xxx.php?callback=?',function(data){ //請求json類型的數(shù)據(jù),支持jsonp的形式:指定?callback=?data }); 隨機({}); </script>jQuery中的插件
擴展插件
//$.extend?:?擴展工具方法下的插件形式??$.xxx()?$.yyy()
//$.fn.extend??:??擴展到JQ對象下的插件形式??$().xxx()??$().yyy()
用插件實現(xiàn)去掉左空格
$.extend({leftTrim : function(str){return str.replace(/^\s+/,''); //這里用正則來去掉左空格} }); var str = ' hello '; alert( '('+$.leftTrim(str)+')' ); //利用leftTrim去掉左空格 $.extend({ //用extend,json的寫法,可以擴展多個leftTrim : function(str){return str.replace(/^\s+/,''); //這里用正則來去掉左空格},rightTrim : function(){},aaa : function(){alert(1);} });$.fn.extend({??//也是寫成json形式
drag : function(){ //這里擴展拖拽//this : $('#div1')var disX = 0;var disY = 0;var This = this; //這里將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);} }); //$.trim() //$.leftTrim() /*var str = ' hello '; alert( '('+$.leftTrim(str)+')' );*/ $(function(){$('#div1').drag(); //這里調(diào)用上面插件的擴展 }); $.aaa(); // 1 $().aaa(); //2轉(zhuǎn)載于:https://www.cnblogs.com/webcome/p/5484005.html
總結(jié)
以上是生活随笔為你收集整理的jquery基本操作笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redis安装及基本配置
- 下一篇: poj1769 线段树优化的dp