欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

各瀏覽器對(duì)document.getElementById等方法的實(shí)現(xiàn)差異解析

 更新時(shí)間:2013年12月05日 09:36:11   作者:  
這篇文章主要是對(duì)各瀏覽器對(duì)document.getElementById等方法的實(shí)現(xiàn)差異進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助

所有Web前端同仁對(duì) document.getElementById 都非常熟悉了。開發(fā)過程中經(jīng)常需要用其獲取頁(yè)面id為xx的元素,自從元老級(jí)JS庫(kù)Prototype流行后,都喜歡這么簡(jiǎn)寫它

復(fù)制代碼 代碼如下:

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

有沒有人想過為什么要這么寫,而不用下面的方式寫呢?
復(fù)制代碼 代碼如下:

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

這么寫的$更簡(jiǎn)潔啊,也很明了,將document的方法getElementById賦值給變量$,用$去獲取頁(yè)面id為xx的元素。實(shí)際上方式2在IE6/7/8中是可行的(IE9中有些變動(dòng)),F(xiàn)irefox/Safari/Chrome/Opera則行不通。還請(qǐng)自行測(cè)試。

為什么Firefox/Safari/Chrome/Opera 方式2獲取就不行呢,原因是這些瀏覽器中g(shù)etElementById方法內(nèi)部實(shí)現(xiàn)中需依賴this(document),IE則不需要this。或者說方式2在Firefox/Safari/Chrome/Opera中調(diào)用時(shí)說丟失了this,以下是個(gè)簡(jiǎn)單示例

復(fù)制代碼 代碼如下:

// 定義一個(gè)函數(shù)show
function show(){alert(this.name);}

// 定義一個(gè)p對(duì)象,有name屬性
var p = {name:'Jack'};

show.call(p); // -> 'Jack'
show(); // -> ''
show.call(null); // -> ''<BR>

可以看到show的實(shí)現(xiàn)中依賴this(簡(jiǎn)單說方法體中使用了this),因此調(diào)用時(shí)的環(huán)境(執(zhí)行上下文)如果沒有name屬性,則得不到期望的結(jié)果。
換句話說,IE6/7/8實(shí)現(xiàn)document.getElementById時(shí)沒有用到this,而 IE9/Firefox/Safari/Chrome/Opera 需要用到this,這里的this正是document對(duì)象。直接調(diào)用方式2時(shí)內(nèi)部的 this卻是window對(duì)象,所以造成方式2在 Firefox/Safari/Chrome/Opera 不能根據(jù)id來正常獲取元素。

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

復(fù)制代碼 代碼如下:

// 修復(fù)document.getElementById
document.getElementById = (function(fn){
    return function(){ 
        return fn.apply(document,arguments);
    };
})(document.getElementById);

// 修復(fù)后賦值給$,$可正常使用了
var $ = document.getElementById;

再次,ECMAScript5 中為function新增的 bind 方法可以實(shí)現(xiàn)同樣的效果
復(fù)制代碼 代碼如下:

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

但目前方式3只有IE9/Firefox/Chrome/支持。

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

復(fù)制代碼 代碼如下:

var prinf = document.write;
prinf('<h3>Test prinf</h3>'); // IE6/7/8可運(yùn)行,其它瀏覽器報(bào)錯(cuò)

var prinfln = document.writeln;
prinfln('<h3>Test prinfln</h3>'); // IE6/7/8可運(yùn)行,其它瀏覽器報(bào)錯(cuò)

var reload = location.reload;
reload(); // IE6/7/8可運(yùn)行,其它瀏覽器報(bào)錯(cuò)

var go = history.go; 
go(-2); // IE6/7/8可運(yùn)行,其它瀏覽器報(bào)錯(cuò)

相關(guān)文章

最新評(píng)論