各浏览器中对document.getElementById等方法的实现差异
所有的Web前端同仁对 document.getElementById 都非常熟悉了。
开发过程中经常需要用其获取页面id为xx的元素,自从元老级js库Prototype流行后,都喜欢这么简写它
// 方式1function $(id){ return document.getElementById(id); }?
有没有人想过为什么要这么写,而不用下面的方式写呢?
// 方式2var $ = document.getElementById;
// 定义一个函数showfunction show(){alert(this.name);}// 定义一个p对象,有name属性var p = {name:'Jack'};show.call(p); // -> 'Jack'show(); // -> ''show.call(null); // -> ''// 修复document.getElementByIddocument.getElementById = (function(fn){ return function(){ return fn.apply(document,arguments); };})(document.getElementById);// 修复后赋值给$,$可正常使用了var $ = document.getElementById;?上面说到IE9有些变动。的确,IE9的情形和Firefox/Safari/Chrome/Opera是一样的,使用方式2将获取不了元素。// 方式3var $ = document.getElementById.bind(document);
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可运行,其它浏览器报错???
1 楼 L--A--N--G 2010-09-28 牛。拜读了