JavaScript getElementById 函数重载 [英] JavaScript getElementById function overload

查看:99
本文介绍了JavaScript getElementById 函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的旧网站有问题.它上面的所有 JavaScript 代码都使用 getElemenById 函数.但是站点标记的标签没有 id 属性,而只有 name 属性.虽然它仍然适用于 IE,但浏览器甚至通过 name 属性返回元素.对于所有其他浏览器,这是 JS 中的错误.请问有什么办法可以在其他浏览器中重载这个功能,让网站兼容其他浏览器吗?

I have a problem with old website. All JavaScript code on it use getElemenById function. But tags of site markup doen't have id property, instead they have only name property. Although it still works for IE, browser returns elements even by name property. For all other browsers it's a mistake in JS. I wonder if there any way to overload this function in other browser to make web site compatible to other browsers?

推荐答案

在 JavaScript 中没有办法重载"函数,因为您可以在 Java 或 C 等强类型语言中这样做.事实上,在这个意义上,JavaScript 中的每个函数都已经重载了,因为您可以使用任意数量和类型的参数调用任何函数.

There's no way to "overload" a function in JavaScript in the sense that you would do so in a strongly-typed language like Java or C. In fact, every function in JavaScript is already overloaded in this sense in that you can call any function with any number and type of arguments.

然而,您可以做的是在现有版本之前插入您自己的代理,并以您喜欢的任何行为实现代理.例如:

What you can do, however, is insert your own proxy in front of the existing version, and implement the proxy with whatever behavior you prefer. For instance:

document._oldGetElementById = document.getElementById;
document.getElementById = function(elemIdOrName) {
    var result = document._oldGetElementById(elemIdOrName);
    if (! result) {
        var elems = document.getElementsByName(elemIdOrName); 
        if (elems && elems.length > 0) {
            result = elems[0];
        }
    }

    return result;
};

这篇关于JavaScript getElementById 函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆