標籤:jquery
如果要比喻jQuery和原生javascript的關係,我個人認為是自動檔和手動檔汽車的區別。使用原生javascript,可以知道離合器以及檔位的作用;而使用jQuery,則把離合器和手動檔位封裝到函數,直接前進、後退或駐車即可。所以,熟練使用原生javascript,再去使用jQuery是一個很自然的步驟。從本文開始,將陸續介紹jQuery的相關內容,並給出相關的原生javascript實現。接下來,將詳細介紹jQuery對象$
$對象
說起jQuery,最明顯的標誌,毫無疑問,就是貨幣符號$,貨幣符號$其實是jquery的簡寫。而使用$()封裝的對象就是jQuery對象
與jQuery對象相對應的就是DOM對象,DOM對象其實就是DOM元素節點對象
如果直接寫document,則指的是document的DOM元素對象
document.onclick = function(){ alert(‘dom‘);}
而如果用$()包括起來,如$(document),是jQuery(document)的簡寫形式,則指的是jQuery對象
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;float:left;border:none;" />
<script src="jquery-3.1.0.js"></script> <script> console.log(jQuery(document));//[document] console.log($(document));//[document] console.log(document);//#document</script>
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;float:left;border:none;" />
[注意]jQuery對象無法使用DOM對象的方法,DOM對象也無法使用jQuery對象的方法
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;float:left;border:none;" />
<script src="jquery-3.1.0.js"></script> <script> //無反應 $(document).onclick = function(){ alert(0); }; //Uncaught TypeError: document.click is not a function document.click(function(){ alert(1); });</script>
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;float:left;border:none;" />
轉換
【1】DOM轉jQuery對象
對於一個jQuery對象,只需要用$()把DOM對象封裝起來,就可以獲得一個jQuery對象
【2】jQuery轉DOM對象
jQuery是一個類數組對象,可以通過[index]或get(index)的方法得到相應的DOM對象
console.log(document === $(document)[0]);//trueconsole.log(document === $(document).get(0));//true
共存
如果jQuery對象和DOM對象指向同一對象,綁定不同函數,則函數會按照順序依次執行
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;float:left;border:none;" />
//先彈出0,再彈出1document.onclick = function(){ alert(0);}$(document).click(function(){ alert(1);});
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;float:left;border:none;" />
不報錯
如果使用DOM對象,為不存在的DOM對象設定樣式會報錯
//Uncaught TypeError: Cannot read property ‘style‘ of nulldocument.getElementById(‘test‘).style.color = ‘red‘;
而使用jQuery對象,為不存在的jQuery對象設定樣式不會報錯
$(‘#test‘).css(‘color‘,‘red‘);
判斷存在
一般地,DOM對象在使用之前需要判斷存在,防止出錯
if(document.getElementById(‘#test‘)){ document.getElementById(‘#test‘).style.color = ‘red‘;}
對於jQuery對象來說,因為$()擷取到的永遠是對象,即使網頁上沒有該元素。所以不能採用下面方式判斷
if($(#test)){ //}
應該根據擷取到元素的長度來判斷
if($(#test).length){ //}
或者轉換成DOM對象來判斷
if($(#test)[0]){ //}
理解jQuery對象$.html