jquery基本操做筆記

jqjsjavascript

能夠共存,不能混用php

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

方法函數化css

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()  由於方法函數法的思想的存在() 是不能省去的,運行函數;這jquery中很常見;html

jsjquery的關係java

能夠互存,不能混用;jquery

 $(function(){
    $('#div1').click(function(){
        //alert( $(this).html() );  //jq的寫法;
        //alert( this.innerHTML );  //js的寫法;這樣寫也是正確的;
        alert( $(this).innerHTML );  //錯誤的;前面是jquery,後面是js,混用了,不容許;
        alert( this.html() );  //錯誤的;前面是js,後面是jquery,混用了,不容許;
    });
});

鏈式操做ajax

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

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

取值和賦值合體:數組

賦值和取值用的同一種方法,只不過是經過有沒有參數來決定是取值仍是賦值;瀏覽器

$(function(){
    //oDiv.innerHTML = 'hello';  //賦值
    //alert( oDiv.innerHTML );  //取值
    //$('#div1').html('hello');  //賦值
    //alert( $('#div1').html() ); //取值
    css('width','200px')  //設置width是200px;
    css('width')  //獲取width的值;
});

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

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

$()下的經常使用方法

attr()

$(function(){
    //alert($('div').attr('title'));  獲取title屬性
    $('div').attr('title','456');  //設置title
    $('div').attr('class','box');  //設置class
});

filter:過濾

notfilter的反義詞

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

hasfilter的區別

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

nextprev

next選擇下一個兄弟節點

prex選擇上一個兄弟節點

find    查找當前元素下全部的後代元素

eq()    一組中的第幾個;

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

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

選項卡:

原生jsjquery

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

也能夠用其餘的思路來作這個選項卡,用到siblings()等;

addClassremoveClass

$(function(){
    $('div').addClass('box2 box4');
    $('div').removeClass('box1');
});

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

$(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是剪切的功能,不是複製的功能;

$(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()  刪除節點

$(function(){
    $('div').remove(); 
});

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

off取消事件;

$(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()   獲取和設置滾動距離

$(function(){
    $(document).click(function(){
        alert( $(window).scrollTop() );  //獲取滾動距離
    });
});

編寫彈窗效果:

首先,在DOM中建立元素是很是容易的事情;

var oDiv = $('<div>div</div>');  //建立div元素和內容
$('body').append( oDiv );

彈窗效果:

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

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

$(function(){
    //div2.offsetLeft
    //alert( $('#div2').offset().left );  //獲取到屏幕的左距離  offset().left  offset.top()
    alert( $('#div2').position().left );  //到有定位的父級的left值,把當前元素轉化成相似定位的形式,注意是不算margin的
});

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

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

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

$(function(){
    //parent() : 獲取父級
    //offsetParent() : 獲取有定位的父級
    //$('#div2').parent().css('background','blue');
    $('#div2').offsetParent().css('background','blue');
});

val()  獲取元素的value值;

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

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

$(function(){
    //alert( $('input').val() ); 獲取value值
    //$('input').val(456);  賦值value值
    alert( $('li').size() );  //4 獲取一組元素的長度;像length
    $('li').each(function(i,elem){   //一參:下標 二參 : 每一個元素
        $(elem).html(i);
    });
});

拖拽jquery實現:

$(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()    指定到一個範圍,有兩個參數,第一個是時間,第二個是透明度值

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

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

 

get()方法

$(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與原生的區別:

$(function(){
    //alert( $('#div1').get(0).offsetWidth );  //這裏原生js,若是把div1設置爲隱藏,獲取的值爲0;
    alert( $('#div1').outerWidth() );  //無論是顯示和隱藏的,均可以獲取到值;
});

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

$(function(){
    //alert( $('div').html() );
    //alert( $('div').text() );  //會獲取全部的內容(特例)
    $('div').text('<h3>h3</h3>');  //在瀏覽器中會輸出純文本<h3>h3</h3>
});

remove()detach()的區別:

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

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

$(function(){
    $('div').click(function(){
        alert(123);
    });
    var oDiv = $('div').detach();  //這裏若是用remove(),恢復的時候,點擊行爲會無效
    $('body').append( oDiv );
});

$()   :  $(document).ready()  window.onload=function(){}的區別:

$(function(){  //等DOM加載完就能夠執行了 , 性能要好
});
是
$(document).ready(function(){
});
的簡寫;

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

//DOMContentLoaded

parents()   closest()

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

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

$(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() : 截止

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

clone()  克隆節點:

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

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

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

serialize()    serializeArray()   數據串連化

$(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(勻速) ) 默認是緩衝(慢快慢)

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

$(function(){
    $('#div1').click(function(){
        $(this).animate({width : 300 , height : 300} , 3000 , 'linear',function(){
            alert(123);   //回調函數,也能夠用鏈式操做來寫;
        });
        $('#div2').animate({width : 300 , height : 300} , 3000 , 'swing');
    });
});

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

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

Stop()方法:

$('#div2').click(function(){
        //$('#div1').stop();   //默認 : 只會阻止當前運動(當前步驟)
        //$('#div1').stop(true); //阻止全部後續的運動
        //$('#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()  主動觸發

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

事件細節:

$(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這個數組中的位置;若沒有會返回-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獨有的

//noConflict() : 防止衝突的
var aaa= $.noConflict(); 
var $ = 10;
aaa(function(){
    aaa('body').css('background','red');
});

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

var str = '{"name":"hello"}';  //字符串必須是嚴格的JSON格式
alert($.parseJSON( str ).name);  //把字符串轉換成json

makeArray() 

window.onload = function(){
    var aDiv = document.getElementsByTagName('div');  //只是集合,不是真正的數組,咱們叫作類數組(相似於數組)
    $.makeArray(aDiv).push();  //經過 $.makeArray(aDiv) 把 類數組 轉換成 真正的數組
};

jquery中使用ajax

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

用插件實現去掉左空格

$.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();  //這裏調用上面插件的擴展
});
$.aaa();  // 1
$().aaa();  //2
相關文章
相關標籤/搜索