天天看點

jQuery study note 1

jQuery           

1 關于text(),傳回選擇元素結果集,實際就是該jq obj對象内的html可視内容;

2 關于選擇器。大部分時間,都把jQuery() or $(),用作選擇器,實際上,配合appendTo(),還可以實作動态建立元素,如

$('<div>I am a div element</div>').appendTo('body');           

這裡建立後,新元素處于body 元素的最後。

3 檢視目前jQuery版本号:$.fn.jquery;$().jquery;jQuery.fn.jquery;jQuery().jquery。

4 $在非正常的dom 文檔模型下是會出現異常的,是以,建議使用html5的文檔模型

<!DOCTYPE html>           

5 何時引入jquery腳本。從1.3起,ready()并不能保證目前所有的css檔案都已經被加載,是以,如果使用1.3以後版本的jquery,須在引入腳本前引入所有css檔案。

6 關于文檔是否準備好,以下三個用法,标明了dom加載狀态,主要是由于事件window.onload是否執行的緣故。文檔加載完成,并不代表window加載完成。

jQuery(document).ready(function(){
     alert('DOM is ready!');
});
jQuery(function(){
     alert('No really, the DOM is ready!');
});
jQuery(function($){
    alert('Seriously its ready!');
});           

是以,在使用的時候,要注意差別,根據實際環境來使用。

7 關于引入腳本的非壓縮版本和壓縮版本的差別。當開發時,使用非壓縮的,有助于調試錯誤,而生産環境,則使用壓縮的,加快頁面加載速度。如下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>           

8 load()與unload()。當window加載完成時,使用load()執行腳本,當使用者離開也即關閉頁面是,使用unload()執行腳本。如下:

jQuery(window).load(function(){alert('Window already loaded!');});
jQuery(window).unload(function(){alert('Bye now!');});           

注意,這裡的load()和ajax的load()是不同的表現。

9 jquery 對象鍊。使用完jQuery的一個方法後,傳回的依舊是一個jquery對象。

10 匿名函數,jQuery的别名$。如下(不會存在沖突):

(function($){})(jQuery);           
(function(){})();           

11 end()的用法。釋放距離最近的一個選擇器所傳回的對象,傳回上一級選擇器傳回的對象。如下:

(function($){
$('#list') // Original wrapper set
    .find('> li') // Destructive method
        .filter(':last') // Destructive method
            .addClass('last')
        .end() // End .filter(':last')
        .find('ul') // Destructive method
            .css('background', '#ccc')
                .find('li:last') // Destructive method
                    .addClass('last')
                .end() // End .find('li:last')
        .end() // End .find('ul')
    .end() // End .find('> li')
.find('li') // Back to the orginal $('#list')
    .append('I am an <li>');

})(jQuery);           

12 jQuery函數的多面性。選擇、建立、ready()時間的捷徑。如下:

jQuery(function($){ // Pass jQuery a function
// Pass jQuery a string of HTML
$('<p></p>').appendTo('body');
// Pass jQuery an element reference
$(document.createElement('a')).text('jQuery').appendTo('p');
// Pass jQuery a CSS expression
$('a:first').attr('href', 'http://www.jquery.com');
// Pass jQuery DOM reference
$(document.anchors[0]).attr('jQuery');
});           

13 this和$(this)的差別。當你的腳本裡目前對象唯一時,使用兩者皆可。如果使用each(),對象在變化中,則需要使用$(this)來擷取動态的目前對象。

14 擷取對象集中的某一個順序元素對象,有三種方法:

$('a').[0];
$('a').get(0);
$('a').eq(0);           

注意,其中,[0]、get(0)傳回的為dom對象,而非jQuery對象,而eq(0)則傳回jQuery對象,可以繼續進行jQuery鍊操作。

15 元素屬性設定。一般使用attr('a', 'b')的形式,但是,還可以使用如下方式,隻是,隻适用于html存在的屬性。

$('a')[0].target = '_self'           

16 (今天就note到這裡)

繼續閱讀