gpt4 book ai didi

javascript - 覆盖 native Javascript 函数

转载 作者:行者123 更新时间:2023-11-30 05:58:06 24 4
gpt4 key购买 nike

具体来说,我想覆盖除 IE 之外的所有浏览器都可用的 getElementsByClassName 函数。 IE 使用 querySelectorAll 代替。

Element.prototype.getElementsByClassName = function(className) {
if(document.getElementsByClassName) {
return this.getElementsByClassName(className);
} else if(document.querySelectorAll) {
return this.querySelectorAll(className);
}
};

但是在 Firefox 中运行代码时,它使用的是 native 函数。如果 getElementsByClassName 不可用,这是否仍然可以用作跨浏览器解决方案并使用我的原型(prototype),或者是否有方法覆盖 native 函数以便每次都使用我的代码?我可以为原型(prototype)命名一个相似的名称,但为了便于阅读,我更愿意保持相同。

最佳答案

我只是想将 Matt Ball 的回答添加为这个问题的真正可接受的答案。正如他提到的,最好使用 polyfill 而不是我最初设置它的方式。

if(!Element.prototype.getElementsByClassName) {
Element.prototype.getElementsByClassName = function(className) {
return this.querySelectorAll(className);
}
}

关于javascript - 覆盖 native Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10576731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com