'HTML元素'在IE8中未定义

'HTMLElement' is undefined in IE8, an alternative?

本文关键字:未定义 IE8 元素 HTML      更新时间:2023-09-26

嘿,我有这样的方法:

// Has Class
HTMLElement.prototype.hasClass = function (searchClass) {
    return this.className.match(new RegExp('(''s|^)' + searchClass + '(''s|$)'));
}

在IE9中运行良好。在IE8中,它给了我未定义的。。。周围有简单的工作吗?

如果我没记错的话,你不能在旧版本的IE中向HTMLElement.prototype添加方法。一个简单的解决方法是:

var hasClass = function (el, searchClass) {
    return el.className.test(new RegExp('(''s|^)' + searchClass + '(''s|$)'));
};

使用方式类似:

alert(    hasClass(   document.getElementById('div1'), 'classToCheck'   )    )

演示

您总是可以将其添加到Object.prototype对象中,但它不适合