重写本机Javascript函数
具体地说,我想覆盖除IE之外的所有浏览器中可用的重写本机Javascript函数,javascript,Javascript,具体地说,我想覆盖除IE之外的所有浏览器中可用的getElementsByClassName函数。IE使用querySelectorAll Element.prototype.getElementsByClassName = function(className) { if(document.getElementsByClassName) { return this.getElementsByClassName(className); } else if(docu
getElementsByClassName
函数。IE使用querySelectorAll
Element.prototype.getElementsByClassName = function(className) {
if(document.getElementsByClassName) {
return this.getElementsByClassName(className);
} else if(document.querySelectorAll) {
return this.querySelectorAll(className);
}
};
但是在Firefox中运行代码时,它使用本机函数。如果GetElementsByCassName不可用,这仍然可以作为跨浏览器解决方案使用我的原型,还是有办法覆盖本机函数以便每次都使用我的代码?我可以给原型取一个类似的名字,但为了便于阅读,我更愿意保持原样。我只想添加马特·鲍尔的答案,作为这个问题的真正公认答案。正如他提到的,最好使用polyfill,而不是我最初设置的方式
if(!Element.prototype.getElementsByClassName) {
Element.prototype.getElementsByClassName = function(className) {
return this.querySelectorAll(className);
}
}
为什么不使用真正的垫片(polyfill)?也就是说:
如果(!Element.prototype.getElementsByClassName){Element.prototype.getElementsByClassName=function(){…};}
您感到困惑,getElementsByClassName是一个方法,而不是一个方法。@MattBall不要使用此方法。您不能期望能够以这种方式修改宿主对象或方法(研究Prototype.js为什么将其作为一种策略放弃)。如果尝试了,你至少应该包括彻底的特性测试。我想我有点困惑了。尽管如此,我还是需要这个函数,这也是我尝试跨浏览器解决方案的原因。这不是一个特别好的解决方案,因为许多浏览器没有为DOM对象(通常是那些没有getElementsByClassName的对象)实现原型固有方案。它还缺乏适当的特征检测,这是必不可少的。你应该再看看polyfill是如何工作的@RobG你有更好的解决方案吗?你不介意分享吗?我最初的做法是最好的吗?写一个简单的函数,提供相同的功能。如果你不能做到这一点(应该不到一个小时,包括测试和文档),网上有很多例子。