jQuery高級技巧——DOM操作篇


 

頁面加載之DOMReady事件

所謂domReady,也就是文檔就緒,我們都知道,在操作dom時必須要在dom樹加載完成后才能進行操作。如何檢測DOM樹已經構建完成,以下是一些實現的方式:

1.使用jQuery:

// with jQuery
$(document).ready(function(){ /* ... */ });
// shorter jQuery version
$(function(){ /* ... */ });

2.監聽DOMContentLoaded事件,DOM 樹創建完成后會觸發,不支持IE10以下版本。

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
// your code goes here
}, false);

3.監聽readyState狀態,可實現跨瀏覽器

readyState 的狀態屬性:

  • "uninitialized" – 原始狀態
  • "loading" – 下載數據中
  • "loaded" – 下載完成
  • "interactive" – 還未執行完畢
  • "complete" – 腳本執行完畢
r(function(){
  alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

這個方法是不斷監聽readyState的loading狀態,加載完成后則執行對應方法。具體可參考:http://www.dustindiaz.com/smallest-domready-ever

根據特定頁面的執行對應的代碼

如果所有頁面的代碼都寫在一個JavaScript文件中,這樣的代碼就會難以維護。簡單的辦法就是根據不同的頁面執行不同的代碼。來看下例子:

例如在test.js有以下代碼:

var route = {
        _routes: {}, // The routes will be stored here
        add: function(url, callback) {
            this._routes[url] = callback;
        },
        run: function() {
            jQuery.each(this._routes, function(pattern) { // pattern 指向_routes對象集合的key,即url
                if (location.href.match(pattern)) {
                    // "this" points to the function to be executed
                    this(); //this 指向指向 _routes對象集合的value,即要執行的方法
                }
            });
        }
    }
    // Will execute only on this page:
route.add('test.html', function() {
    alert('Hello there!');
});
route.add('products.html', function() {
    alert("this won't be executed :(");
});
// You can even use regex-es:
route.add('.*.html', function() {
    alert('This is using a regex!');
});
route.run();

使用邏輯與運算符

利用邏輯與運算符可以簡化條件分支語句寫法,例子:

一般的寫法:

// Instead of writing this:
if($('#elem').length){
   // do something
}

更好的寫法:

$('#elem').length && alert("doing something");

非常有用的jquery is()方法

is()方法非常有用,來看些例子:

HTML:

<div id="elem"></div>

JS:

// 變量保存jQuery對象
var elem = $('#elem');
// 判斷是否為div
elem.is('div') && console.log("it's a div");
// 是否包含類名.bigbox
elem.is('.bigbox') && console.log("it has the bigbox class!");
// 是否可見
elem.is(':not(:visible)') && console.log("it is hidden!");
// 設置元素執行動畫
elem.animate({'width':200},1);
// 是否執行動畫
elem.is(':animated') && console.log("it is animated!");

定義一個exists函數

判斷一個jQuery對象是否存在需要判斷length屬性,可以封裝為exists函數,簡化代碼,更加易讀。

HTML:

<div id="elem"></div>

JS:

//一般方法
console.log($('#elem').length == 1 ? "exists!" : "doesn't exist!");
// 封裝方法
jQuery.fn.exists = function(){ return this.length > 0; }
console.log($('#elem').exists() ? "exists!" : "doesn't exist!");

使用$()函數的第二個參數

$()函數可以接收兩個參數,第二個參數的作用是什么,可以來看下例子:

<ul id="firstList" >
      <li>one</li>
      <li>two</li>
      <li>three</li>
</ul>

<ul id="secondList" >
      <li>blue</li>
      <li>green</li>
</ul>

作用一:

//選取一個元素,通過#firstList限制元素只能在當前的ul節點范圍內選取
$('li' , '#firstList' ). each(function(){
    console.log($(this). html());
});
//相當於$('#firstList' ). find('li' );

作用二:

//創建一個元素。第二個參數為對應的配置屬性,包含jQuery方法會被執行
var div = $('<div>' ,{
 "class" : "bigBlue" ,
 "css" : {
 "background-color" : "purple"
 },
 "width" : 20,
 "height" : 20,
 "animate" : { //使用jQuery的方法作為屬性
 "width" : 200,
 "height" : 50
 }
});

div. appendTo('body' );

取消右鍵Click事件

$(function(){
    $(document).on("contextmenu" , function(e){
             e. preventDefault();
    });
});

取消文本選中

//適應於所有瀏覽器
$('p.descr' ). attr('unselectable' , 'on' ) . css('user-select' , 'none' ) . on('selectstart' , false);

解析錨元素URL

// 需要解析的URL
var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments' ;

// 通過url創建一個新的鏈接
var a = $('<a>' ,{ href:  url });

console. log('Host name: ' + a. prop('hostname' ));
console. log('Path: ' + a. prop('pathname' ));
console. log('Query: ' + a. prop('search' ));
console. log('Protocol: ' + a. prop('protocol' ));
console. log('Hash: ' + a. prop('hash' ));

輸出結果:

Host name: tutorialzine.com
Path: /books/jquery-trickshots
Query: ?trick=12
Protocol: http:
Hash: #comments

以上是一些知識總結,如有任何建議或疑問,歡迎留言討論。

參考鏈接:

http://www.cnblogs.com/rubylouvre/p/4277408.html

http://www.dustindiaz.com/smallest-domready-ever


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM