各瀏覽器對document.getElementById等方法的實現差異

來源:互聯網
上載者:User

所有Web前端同仁對 document.getElementById 都非常熟悉了。開發過程中經常需要用其擷取頁面id為xx的元素,自從元老級JS庫Prototype流行後,都喜歡這麼簡寫它

// 方式1function $(id){ return document.getElementById(id); }

有沒有人想過為什麼要這麼寫,而不用下面的方式寫呢?

// 方式2var $ = document.getElementById;

這麼寫的$更簡潔啊,也很明了,將document的方法getElementById賦值給變數$,用$去擷取頁面id為xx的元素。實際上方式2在IE6/7/8中是可行的(IE9中有些變動),Firefox/Safari/Chrome/Opera則行不通。還請自行測試。

為什麼Firefox/Safari/Chrome/Opera 方式2擷取就不行呢,原因是這些瀏覽器中getElementById方法內部實現中需依賴this(document),IE則不需要this。或者說方式2在Firefox/Safari/Chrome/Opera中調用時說丟失了this,以下是個簡單樣本

// 定義一個函數showfunction show(){alert(this.name);} // 定義一個p對象,有name屬性var p = {name:'Jack'}; show.call(p); // -> 'Jack'show(); // -> ''show.call(null); // -> ''

可以看到show的實現中依賴this(簡單說方法體中使用了this),因此調用時的環境(執行內容)如果沒有name屬性,則得不到期望的結果。
換句話說,IE6/7/8實現document.getElementById時沒有用到this,而 IE9/Firefox/Safari/Chrome/Opera 需要用到this,這裡的this正是document對象。直接調用方式2時內部的 this卻是window對象,所以造成方式2在 Firefox/Safari/Chrome/Opera 不能根據id來正常擷取元素。

如果將document.getElementById的 執行環境換成了document而非window,則可以正常的使用$了。如下

// 修複document.getElementByIddocument.getElementById = (function(fn){    return function(){         return fn.apply(document,arguments);    };})(document.getElementById); // 修複後賦值給$,$可正常使用了var $ = document.getElementById;

再次,ECMAScript5 中為function新增的 bind 方法可以實現同樣的效果

// 方式3var $ = document.getElementById.bind(document);

但目前方式3隻有IE9/Firefox/Chrome/支援。

分析了getElementById的情況,下面的一些方法在各瀏覽器中的差異原因就很好明白了

var prinf = document.write;prinf('<h3>Test prinf</h3>'); // IE6/7/8可運行,其它瀏覽器報錯 var prinfln = document.writeln;prinfln('<h3>Test prinfln</h3>'); // IE6/7/8可運行,其它瀏覽器報錯 var reload = location.reload;reload(); // IE6/7/8可運行,其它瀏覽器報錯 var go = history.go; go(-2); // IE6/7/8可運行,其它瀏覽器報錯

轉自: http://www.cnblogs.com/snandy/archive/2011/03/24/1993380.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.