这是一段可以追溯到 Netscape Navigator 时代的 js 代码。我无法弄清楚或找到这个人这样做的原因。
function id(i)
{
var e;
if (document.getElementById)
return document.getElementById(i);
else if (document.all)
return document.all[i];
else if (document.layers)
return document.layers[i];
return null;
}
Run Code Online (Sandbox Code Playgroud)
在较新的浏览器中,if(document.getElementById)总是如此。看起来它正在检查该功能是否存在,但我不确定。
我问的原因是因为这段代码从 IE8 及更低版本的浏览器中读取name(不是 id)不应具有 name 属性的元素。我的任务是尝试让它在较新的浏览器上更有效地工作。但首先,我真的需要了解这段代码的含义。
读取name诸如 a之类的from 属性<tr>是在别处完成的,这是将其用作自定义属性的非常简单的修复。我包含的这件作品涉及更多作品,并不那么简单。
这是一种特征检测形式getElementById- 几乎:
function id(i)
{
var e;
if (document.getElementById) // the standard way
return document.getElementById(i);
else if (document.all) // old IE model, needed for very old IE versions
return document.all[i];
else if (document.layers) // old netscape model, Netscape 4 etc.
return document.layers[i];
return null;
}
Run Code Online (Sandbox Code Playgroud)
除非您支持 IE < 5.5 或 Netsape < 6 ,否则您不应该完全支持这两者 - 今天您应该避免这种形式的特征检测。
这种代码在今天很常见,以执行特征检测。我想强调一个事实,即该代码在编写时是最佳实践,但今天已无用。例如,今天你有这样的事情:
if ( !window.requestAnimationFrame ) {
window.requestAnimationFrame = ( function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback,element) {
window.setTimeout( callback, 1000 / 60 );
};
} )();
}
Run Code Online (Sandbox Code Playgroud)
执行完全相同的操作,仅适用于较新的 API。