JavaScript getElementById function overload

混江龙づ霸主 提交于 2019-12-13 03:44:11

问题


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?


回答1:


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;
};



回答2:


I wouldn't count on overriding getElementById working properly. Sounds easy enough to do a search and replace that does something like this:

// Replace
document.getElementById("foo");
// With
myGetElementById("foo", document);

// Replace
myElement.getElementById("foo");
// With
myGetElementById("foo", myElement);

Then you can myGetElementById as you want, without worrying about what might happen in old IEs and what not if you override getElementById.




回答3:


Try getElementsByName. This is used to get a collection of elements with respect to their name



来源:https://stackoverflow.com/questions/6855466/javascript-getelementbyid-function-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!