所有Web前端同仁對 document.getElementById 都非常熟悉了。開發過程中經常需要用其獲取頁面id為xx的元素,自從元老級JS庫Prototype流行后,都喜歡這么簡寫它
復制代碼 代碼如下:
// 方式1 
function $(id){ return document.getElementById(id); } 
復制代碼 代碼如下:
// 方式2 
var $ = document.getElementById; 
為什么Firefox/Safari/Chrome/Opera 方式2獲取就不行呢,原因是這些瀏覽器中getElementById方法內部實現中需依賴this(document),IE則不需要this。或者說方式2在Firefox/Safari/Chrome/Opera中調用時說丟失了this,以下是個簡單示例
復制代碼 代碼如下:
// 定義一個函數show 
function show(){alert(this.name);} 
// 定義一個p對象,有name屬性 
var p = {name:'Jack'}; 
show.call(p); // -> 'Jack' 
show(); // -> '' 
show.call(null); // -> ''<BR> 
如果將document.getElementById的 執行環境換成了document而非window,則可以正常的使用$了。如下
復制代碼 代碼如下:
// 修復document.getElementById 
document.getElementById = (function(fn){ 
    return function(){  
        return fn.apply(document,arguments); 
    }; 
})(document.getElementById); 
// 修復后賦值給$,$可正常使用了 
var $ = document.getElementById; 
復制代碼 代碼如下:
// 方式3 
var $ = document.getElementById.bind(document); 
分析了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可運行,其它瀏覽器報錯 
新聞熱點
疑難解答
圖片精選