-1

我正在编写一个自定义方法来返回 DOM 元素引用,但它似乎适用于所有现代浏览器,如 Chrome、Firefox、Safari,但在 IE 9 中失败......返回的元素未定义它表明我不确定我在做什么错误的

var searchEle = function (parent, ref) {
var refEle;
if (typeof document.getElementByClassName === "function") {
    if (ref.substr(0, 1) === ".") {
        refEle = parent.getElementsByClassName(ref.replace(".", ""));
    } else {
        refEle = parent.getElementsByTagName(ref);
    }
} else {
    if (ref.substr(0, 1) === "#") {
        refEle = parent.getElementById(ref.replace("#", ""));
    } else if (ref.substr(0, 1) === ".") {
        refEle = parent.querySelector(ref);
    }
}
return refEle;
};

在 IE9 上查看演示:http: //jsbin.com/ubokop/5/edit

谢谢

4

1 回答 1

1

首先,将这个 polyfill 用于getElementsByClassName,因为这确实是唯一需要一个的函数。它并不完美,但已经足够接近了。

// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
    document.getElementsByClassName = function(search) {
        var d = document, elements, pattern, i, results = [];
        if (d.querySelectorAll) { // IE8
            return d.querySelectorAll("." + search);
        }
        if (d.evaluate) { // IE6, IE7
            pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
            elements = d.evaluate(pattern, d, null, 0, null);
            while (i = elements.iterateNext()) {
                results.push(i);
            }
        } else {
            elements = d.getElementsByTagName("*");
            pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
            for (i = 0; i < elements.length; i++) {
                if ( pattern.test(elements[i].className) ) {
                    results.push(elements[i]);
                }
            }
        }
        return results;
    }
}

这个polyfill的来源

那么,这就足够了:

var searchEle = function (ref) {
    if (ref.charAt(0) === "#") {
        return document.getElementById(ref.substr(1));
    }else if (ref.charAt(0) === ".") {
        return document.getElementsByClassName(ref.substr(1));
    }else{
        return document.getElementsByTagName(ref);
    }
};
于 2013-02-08T12:47:37.183 回答