简体   繁体   中英

what's the meaning of the function?

function hasClass( elem, cls ) {
var reClass = new RegExp(' ' + cls + ' ');
return reClass.test(' ' + elem.className + ' ');
}

i am a new learner of javascript, i saw the above function from a book.but i don't what's the meaning of it? expect someone can explain it to me.many thanks.

It's just testing whether a given element contains a given class. This is useful for elements with multiple classes (older browsers don't support that by default).

Consider an element like <div id='test' class="button login"></div> . If you pass that to the function, you'll get as follows:

function hasClass( elem, cls ) {

    // var reClass = new RegExp(' login ');
    var reClass = new RegExp(' ' + cls + ' ');

    // return reClass.test(' button login ');  (ie, true)
    return reClass.test(' ' + elem.className + ' ');
}
console.log(hasClass(document.getElementById('test'), 'login'));

Demo here

它检查元素的class属性是否包含指定的类(cls)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM