【问题标题】:'HTMLElement' is undefined in IE8, an alternative?'HTMLElement' 在 IE8 中未定义,替代方案?
【发布时间】:2012-02-10 16:27:08
【问题描述】:

嘿,我有这样的方法:

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

在 IE9 中它工作正常。在 IE8 中它给了我 undefined... 有一个简单的解决方法吗?

【问题讨论】:

    标签: javascript internet-explorer-8


    【解决方案1】:

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

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

    并像这样使用:

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

    DEMO

    您始终可以将其添加到 Object.prototype 对象中,但它不受欢迎

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-13
      • 2020-02-09
      • 2016-07-22
      • 2020-02-28
      • 1970-01-01
      • 2018-03-16
      • 2014-07-26
      • 2010-12-12
      相关资源
      最近更新 更多