如何在IE 7和6中按类名获取元素

How to get element by class name in IE 7 & 6

本文关键字:获取 元素 IE      更新时间:2023-09-26

我正在尝试通过类名获取元素,在IE 9+中,我可以使用document.getElementsByClassName,而在IE 8中document.querySelectorAll都可以工作。

上述 2 个函数在 IE 7 中不可用,我正在尝试使用此处提供的 kapa 答案中的想法 getElementsByClassName() 在 IE6、IE7、IE8 等旧 Internet Explorer 中不起作用

下面是我正在尝试的代码"

function getElementsByClassNameBackwardCompatability(className) {
    if (document.getElementsByClassName) {
        return document.getElementsByClassName(className);//EI 9+
    } else if (document.querySelectorAll(className)) {
        return document.querySelectorAll(className);//EI 8
    } else { // IE7 - (not working)
        var d = document, element, pattern;
        pattern = ".//*[contains(concat(' ',@@class, ' '), ' " + className + " ')]";
        element = d.evaluate(pattern, d, null, 0, null);
        return  element;
    }
}`

它在IE 7中抛出错误"JavaScript runtime error: Could not complete the operation due to error 80020101."

以下是我如何使用该功能

     var ddlone = getElementsByClassNameBackwardCompatability(".myClass");
        $(ddlone).dropdownchecklist("destroy");
        $(ddlone).dropdownchecklist({ icon: {}, closeRadioOnClick: true, maxDropHeight: 150});
  $(getElementsByClassNameBackwardCompatability(".myDateClass")).each(function () {
            $(this).datepicker({
                dateFormat: 'dd/mm/yy',
                showButtonPanel: true,
                changeMonth: true,
                changeYear: true,
                defaultDate: new Date(),
            });});

任何我如何在IE 7中使其工作?

该函数采用类名,而不是类选择器 - 没有点。尝试将其称为

getElementsByClassNameBackwardCompatability(".myDateClass")

您确实应该使用该答案中的原始代码,您的代码在导致其不起作用的几个关键方面有所不同。