jquery基本操作筆記

jq和js

可以共存,不能混用

1

2

3

4

5

6

$('.box').css('background','red');

$(".box").css({ color: "#ff0011", background: "blue"});

$('li:eq(2)').css('background','red');  //:first選擇

$('li:odd').css('background','red');  //even奇數行,odd偶數行

$('li').filter('.box').css('background','red');  filter過濾、篩選;

$('li').filter('[title=hello]').css('background','red');

方法函數化

1

2

3

4

5

6

7

8

9

window.onload = function(){};

$(function(){});

function $(){}

innerHTML = 123;

html(123)

function html(){}

onclick = function(){};

click(function(){})

function click(){}

1

2

3

$('#div1').click(function(){

        alert( $(this).html() );

});

jquery中的this的寫法是   $(this)  ;html()  因爲方法函數法的思想的存在,() 是不能省去的,運行函數;這在jquery中很常見;

jsjquery的關係

可以互存,不能混用;

1

2

3

4

5

6

7

8

$(function(){

    $('#div1').click(function(){

        //alert( $(this).html() );  //jq的寫法;

        //alert( this.innerHTML );  //js的寫法;這樣寫也是正確的;

        alert( $(this).innerHTML );  //錯誤的;前面是jquery,後面是js,混用了,不允許;

        alert( this.html() );  //錯誤的;前面是js,後面是jquery,混用了,不允許;

    });

});

鏈式操作

1

2

3

4

5

6

7

8

9

10

11

$(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);

    });

});

建議熟悉了,再寫鏈式寫法;

取值和賦值合體:

賦值和取值用的同一種方法,只不過是通過有沒有參數來決定是取值還是賦值;

1

2

3

4

5

6

7

8

$(function(){

    //oDiv.innerHTML = 'hello';  //賦值

    //alert( oDiv.innerHTML );  //取值

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

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

    css('width','200px'//設置width是200px;

    css('width'//獲取width的值;

});

取值和賦值:獲取的時候只能獲取一個,賦值的時候賦值到所有的;

1

2

3

4

$(function(){

    //alert( $('li').html() );  //當一組元素的時候,取值是一組中的第一個;會彈出內容:aaa

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

});

$()下的常用方法

attr()

1

2

3

4

5

$(function(){

    //alert($('div').attr('title'));  獲取title屬性

    $('div').attr('title','456');  //設置title

    $('div').attr('class','box');  //設置class

});

filter:過濾

not: filter的反義詞

1

2

3

4

$(function(){

    //$('div').filter('.box').css('background','red'); //只帶有box的纔會被選擇

    $('div').not('.box').css('background','red'); //不帶有box的纔會選擇;not和filter是反義詞

});

has和filter的區別

has是包含的意思,選擇的是元素裏面的東西;

而filter針對的元素自身的選擇;

1

2

3

4

5

$(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選擇下一個兄弟節點;

prex選擇上一個兄弟節點;

find    查找當前元素下所有的後代元素;

eq()    一組中的第幾個;

index()  一組元素的索引;通過一組索引,來控制另外一個索引;

1

2

3

$(function(){

    alert( $('#h').index() );  //索引就是當前元素在所有兄弟節點中的位置;

});

選項卡:

原生js和jquery:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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');

    });

});

1

2

3

4

5

6

7

8

9

10

<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是根據js的思路來編寫的;

也可以用其他的思路來做這個選項卡,用到siblings()等;

addClass和removeClass

1

2

3

4

$(function(){

    $('div').addClass('box2 box4');

    $('div').removeClass('box1');

});

width()   innerWidth()   outerWidth()  獲取元素的寬和區別

1

2

3

4

5

6

$(function(){

    alert( $('div').width() );  //width

    alert( $('div').innerWidth() );  //width + padding

    alert( $('div').outerWidth() );  //width + padding + border

    alert( $('div').outerWidth(true) );  //width + padding + border + margin

});

insertBefore()  insertAfter()  

注意:insertBefore是剪切的功能,不是複製的功能;

1

2

3

4

5

6

7

8

9

$(function(){

    //$('span').insertBefore( $('div') );  //將span調整到div的前面,jq中的insertBefore和js中的insertBefore是一樣的;具備剪切的功能,而不是複製的功能;

    //$('div').insertAfter( $('span') );  //將div放在span的後面;

    //$('div').appendTo( $('span') );   //和js中的appendChildren是一樣的;作用是把一個節點添加到指定節點最後的位置;

    //$('div').prependTo( $('span') );  //原生js中沒有,作用是把一個節點添加到指定節點最開始的位置;  

    //insertBefore和before的區別 :後續操作變了;主要是我們寫鏈式操作會有影響;

    //$('span').insertBefore( $('div') ).css('background','red');

    $('div').before( $('span') ).css('background','red');

});

remove()  刪除節點

1

2

3

$(function(){

    $('div').remove();

});

on()  off()   事件的寫法:

off取消事件;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

$(function(){

    /*$('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);

        }

    });*/   //點擊彈出123.移入彈出456  說明on還是很靈活的

    $('div').on('click mouseover',function(){

        alert(123);

        $('div').off('mouseover');  //執行後,mouseover事件會被關閉

    });  

});

scrollTop()   獲取和設置滾動距離

1

2

3

4

5

$(function(){

    $(document).click(function(){

        alert( $(window).scrollTop() );  //獲取滾動距離

    });

});

編寫彈窗效果:

首先,在DOM中創建元素是非常容易的事情;

1

2

var oDiv = $('<div>div</div>');  //創建div元素和內容

$('body').append( oDiv );

彈窗效果:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$(function(){

    $('#input1').click(function(){

        //動態創建元素和內容

        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 );   //設置left值

        oLogin.css('top' , ($(window).height() - oLogin.outerHeight())/2 );  //設置top值

        $('#close').click(function(){

            oLogin.remove();   //移除節點

        });

        //在調整窗口大小事件和滾動事件,調整彈出窗的位置;

        $(window).on('resize scroll',function(){  //在調整窗口大小事件和滾動事件

            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()

1

2

3

4

5

6

7

8

9

10

11

12

13

$(function(){

    /*$('div').click(function(ev){

        //ev : jq中直接使用,是兼容後的event對象

        //ev.pageX(鼠標座標-->相對於文檔的)    js中是使用clientX(相對於可視區域的)

        //ev.which : js中的keyCode

        ev.preventDefault();  //阻止默認事件

        ev.stopPropagation();  //阻止冒泡的操作

        return false;   //阻止默認事件 + 阻止冒泡的操作

    });*/

    $('div').one('click',function(){  //one-->只執行事件一次

        alert(123);

    });

});

offset()  position()

1

2

3

4

5

$(function(){

    //div2.offsetLeft

    //alert( $('#div2').offset().left );  //獲取到屏幕的左距離  offset().left  offset.top()

    alert( $('#div2').position().left );  //到有定位的父級的left值,把當前元素轉化成類似定位的形式,注意是不算margin的

});

parent() offsetParent()   獲取有定位的父級

parent() : 獲取父級,不管父級是否有定位; 注意這裏沒有加s,不是parents,jq中還有parents()方法,見下

offsetParent() : 獲取有定位的父級

1

2

3

4

5

6

$(function(){

    //parent() : 獲取父級

    //offsetParent() : 獲取有定位的父級

    //$('#div2').parent().css('background','blue');

    $('#div2').offsetParent().css('background','blue');

});

val()  獲取元素的value值;

size() 獲取一組元素的長度;像length;

each() jq中的循環;原生for循環的加強版

1

2

3

4

5

6

7

8

$(function(){

    //alert( $('input').val() ); 獲取value值

    //$('input').val(456);  賦值value值

    alert( $('li').size() );  //4 獲取一組元素的長度;像length

    $('li').each(function(i,elem){   //一參:下標 二參 : 每個元素

        $(elem).html(i);

    });

});

拖拽jquery實現:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

$(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         鼠標移入和鼠標移除結合的方法;

hover(function(){},function(){})

 

Show() hide()            接受一個參數- ->  時間(ms)               長,寬,透明度都要變化

fadeIn()   fadeOut()    淡出效果和淡出效果  改變透明度

fadeTo()    指定到一個範圍,有兩個參數,第一個是時間,第二個是透明度值

1

$('#div2').fadeTo(1000,0.5);

slideDown()   slideUp()         向下展開,向上捲起;

 

get()方法

1

2

3

4

5

6

7

8

9

10

11

$(function(){

    //document.getElementById('div1').innerHTML

    //alert( $('#div1').get(0).innerHTML );  get需要標註下標;將jquery轉成原生js

    /*for(var i=0;i<$('li').get().length;i++){  //這裏通過get()轉成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';  得到元素後,後面加一箇中括號,寫成下標的形式,也就自動轉成原生js的形式了;這是一種偷巧的寫法;

    }

});

outerWidth與原生的區別:

1

2

3

4

$(function(){

    //alert( $('#div1').get(0).offsetWidth );  //這裏原生js,如果把div1設置爲隱藏,獲取的值爲0;

    alert( $('#div1').outerWidth() );  //不管是顯示和隱藏的,都可以獲取到值;

});

text()    會獲取所有的內容(特例),不會獲取到標籤,而html會獲取到標籤;

1

2

3

4

5

$(function(){

    //alert( $('div').html() );

    //alert( $('div').text() );  //會獲取所有的內容(特例)

    $('div').text('<h3>h3</h3>');  //在瀏覽器中會輸出純文本<h3>h3</h3>

});

remove()和detach()的區別:

//remove方法刪除元素的時候會把元素的操作行爲也刪除掉;

//detach() : 跟remove方法一樣,只不過會保留刪除這個元素的操作行爲

1

2

3

4

5

6

7

$(function(){

    $('div').click(function(){

        alert(123);

    });

    var oDiv = $('div').detach();  //這裏如果用remove(),恢復的時候,點擊行爲會無效

    $('body').append( oDiv );

});

$()   :  $(document).ready()  與window.οnlοad=function(){}的區別:

1

2

3

4

5

6

$(function(){  //等DOM加載完就可以執行了 , 性能要好

});

$(document).ready(function(){

});

的簡寫;

 window.onload = function(){}; //等圖片和flash等加載完才執行;

//DOMContentLoaded

parents()   closest()

//parents() : 獲取當前元素的所有祖先節點,參數就是篩選功能

//closest() : 獲取最近的指定的祖先節點(包括當前元素自身),必須要寫篩選的參數,只能找到一個元素

1

2

3

4

5

$(function(){

    //$('#div2').parents().css('background','red');  //獲取到所有祖先節點 div1,body,html

    //$('#div2').parents('.box').css('background','red');  //獲取到class爲box的祖先元素

    $('#div2').closest('.box').css('background','red');

});

siblings() 獲取元素的所有兄弟節點 ;

nextAll() 獲取下面所有的兄弟節點;

preAll() 獲取上面所有的兄弟節點;

parentsUntil()   nextUntil()   prevUntil()

//siblings() : 找所有的兄弟節點,參數也是篩選功能

//nextAll() : 下面所有的兄弟節點,參數也是篩選功能

//prevAll() : 上面所有的兄弟節點

//Until() : 截止

1

2

3

$(function(){

    $('span').nextUntil('h2').css('background','red');

});

clone()  克隆節點:

1

2

3

4

5

6

7

8

9

$(function(){

    //$('div').appendTo( $('span') );   //剪切行爲

    //$('span').get(0).appendChild( $('div').get(0) );

    //clone() : 可以接收一個參數 ,作用可以複製之前的操作行爲

    $('div').click(function(){

        alert(123);

    });

    $('div').clone(true).appendTo( $('span') ); //參數true作用可以複製之前的操作行爲

});

wrap()  wrapAll()  wrapInner()  unwrap()   包裝,包裝方法

在外面包裹一下

$('span').wrapInner('<div>'); //在span外包裝div

 wrapAll() 整體包裝:

//wrap() : 包裝

//wrapAll() : 整體包裝; 會影響結構

//wrapInner() : 內部包裝;

//unwrap() : 刪除包裝 ( 刪除父級 : 不能刪除body )

1

2

3

4

$(function(){

    //$('span').wrapInner('<div>');   div在span裏面了

    $('span').unwrap();

});

add()

1

2

3

4

5

6

7

$(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');

第一個參數是起始位置,4是結束位置(選中的不包括結束位置);

serialize()    serializeArray()   數據串連化

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$(function(){

    //console.log($('form').serialize());  //string : a=1&b=2&c=3

    console.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() : 

//第一個參數 : {} 運動的值和屬性

//第二個參數 : 時間(運動快慢的)  默認 : 400 毫秒

//第三個參數 : 運動形式 只有兩種運動形式 ( 默認 : swing(緩衝,慢快慢) linear(勻速) ) 默認是緩衝(慢快慢)

//第四個參數 :  回調函數;運行結束後,回調函數

1

2

3

4

5

6

7

8

$(function(){

    $('#div1').click(function(){

        $(this).animate({width : 300 , height : 300} , 3000 , 'linear',function(){

            alert(123);   //回調函數,也可以用鏈式操作來寫;

        });

        $('#div2').animate({width : 300 , height : 300} , 3000 , 'swing');

    });

});

鏈式操作來寫:先寬後高;和上述的回調函數效果一致;

1

$(this).animate({width : 300} , 2000).animate({height : 300} , 2000);

Stop()方法:

1

2

3

4

5

6

7

$('#div2').click(function(){

        //$('#div1').stop();   //默認 : 只會阻止當前運動(當前步驟)

        //$('#div1').stop(true); //阻止所有後續的運動

        //$('#div1').stop(true,true); //立即停止到當前步驟指定的目標點,當前步驟的目標點

        // stop不能做到,點一下-->直接到最後的目標點-->用finish()

        $('#div1').finish();  //立即停止到所有指定的目標點,到最後的目標點

    });

delay()

延遲

jquery中事件委託:

delegate()   undelegate()

1

2

3

4

5

6

7

8

9

$(function(){

    /*$('li').on('click',function(){

        this.style.background = 'red';

    });*/

    $('ul').delegate('li','click',function(){   //事件委託

        this.style.background = 'red';

        $('ul').undelegate();  //阻止事件委託

    });

});

trigger()  主動觸發

1

2

3

4

5

6

7

8

9

10

11

12

13

$(function(){

    /*$('#div1').on('click',function(){

        alert(123);

    });

    $('#div1').trigger('click');  //主動觸發*/

    $('#div1').on('show',function(){

        alert(123);

    });

    $('#div1').on('show',function(){

        alert(456);

    });

    $('#div1').trigger('show');

});

事件細節:

1

2

3

4

5

6

7

$(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()

1

2

3

4

5

6

7

8

$(function(){

    //var a = null;

    //$.type() : 也是判斷類型,功能更加強大,能判斷出更多的類型

    //alert( typeof a ); 原生js的判斷變量類型

    //alert( $.type(a) ); 用$.type()判斷出更多類型,功能更強大

    var str = '    hello    ';

    alert('('+$.trim(str)+')');  //$.trim()去除前後的空格

});

inArray()   類似於 indexOf

proxy()  改變this指向;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$(function(){

    //var arr = ['a','b','c','d'];

    //alert( $.inArray('b',arr)  ); //b在array這個數組中的位置;若沒有會返回-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)  ); //如果這樣傳參,刷新就直接調用函數

    $(document).click( $.proxy(show,window,3,4)  );  //這樣傳參,就是在click後纔會調用函數,而不會直接調用; 

 

});

$.noConflict()  防止衝突

//$ , jQuery  $=jQuery 一回事 $不是jQuery獨有的

1

2

3

4

5

6

//noConflict() : 防止衝突的

var aaa= $.noConflict();

var $ = 10;

aaa(function(){

    aaa('body').css('background','red');

});

parseJSON()  把字符串轉換成json類型

1

2

var str = '{"name":"hello"}'//字符串必須是嚴格的JSON格式

alert($.parseJSON( str ).name);  //把字符串轉換成json

makeArray() 

1

2

3

4

window.onload = function(){

    var aDiv = document.getElementsByTagName('div');  //只是集合,不是真正的數組,我們叫做類數組(類似於數組)

    $.makeArray(aDiv).push();  //通過 $.makeArray(aDiv) 把 類數組 轉換成 真正的數組

};

jquery中使用ajax

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<script>

/*$.ajax({

    url : 'xxx.php',

    data : 'name=hello&age=20',

    type : 'POST',   //默認是get

    success : function(data){  //請求成功以後的回調函數

        alert(1);

    },

    error : function(){   //請求失敗之後

        alert(2);

    }

});*/

$.get('xxx.php',function(){    //ajax的get請求可用get(),第一個是地址,第二個是成功後回調

});

// $.get()和$().get()是有區別的;前者是ajax的get請求方法,後者是將jQuery對象轉換成js原生對象

$.post('xxx.php',function(){

});

$.getJSON('xxx.php?callback=?',function(data){  //請求json類型的數據,支持jsonp的形式:指定?callback=?

    data

});

隨機({});

</script>

jQuery中的插件

擴展插件

//$.extend : 擴展工具方法下的插件形式  $.xxx() $.yyy()

//$.fn.extend  :  擴展到JQ對象下的插件形式  $().xxx()  $().yyy()

用插件實現去掉左空格

1

2

3

4

5

6

7

$.extend({

    leftTrim : function(str){

        return str.replace(/^\s+/,''); //這裏用正則來去掉左空格

    }

});

var str = '  hello  ';

alert( '('+$.leftTrim(str)+')' );  //利用leftTrim去掉左空格

1

2

3

4

5

6

7

8

9

$.extend({    //用extend,json的寫法,可以擴展多個

    leftTrim : function(str){

        return str.replace(/^\s+/,''); //這裏用正則來去掉左空格

    },

    rightTrim : function(){},

    aaa : function(){

        alert(1);

    }

});

$.fn.extend({  //也是寫成json形式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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);

    }

});

1

2

3

4

5

6

7

8

9

//$.trim()

//$.leftTrim()

/*var str = '  hello  ';

alert( '('+$.leftTrim(str)+')' );*/

$(function(){

    $('#div1').drag();  //這裏調用上面插件的擴展

});

$.aaa();  // 1

$().aaa();  //2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章