问题
Hey all I have methods like this:
// Has Class
HTMLElement.prototype.hasClass = function (searchClass) {
return this.className.match(new RegExp('(\\s|^)' + searchClass + '(\\s|$)'));
}
In IE9 it works fine. In IE8 it gives me undefined... is there a simple work around?
回答1:
You can't add methods to HTMLElement.prototype
in older versions of IE if I remember correctly. A simple workaround would be:
var hasClass = function (el, searchClass) {
return el.className.test(new RegExp('(\\s|^)' + searchClass + '(\\s|$)'));
};
And used like:
alert( hasClass( document.getElementById('div1'), 'classToCheck' ) )
DEMO
You can always add this to the Object.prototype
object but it's frowned on
来源:https://stackoverflow.com/questions/8868004/htmlelement-is-undefined-in-ie8-an-alternative