javascript 如何判断元素是否包含一个特定的类,hasClass函数的实现
刚开始这么写的:
1 function hasClass(element, cls) { 2 var regexp = new RegExp("\\b" + cls + "\\b"); 3 return element.className.search(regexp) !== -1; 4 } // end hasClass()
用\b匹配word boundary,这样可以有效处理"aaa", "aaa bbb"的匹配,但是忘记了word boundary的明确定义
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
在简单的测试中工作得很好,后来写的程序总是不能按照预期的想法工作,花了不少时间才知道原来是这里出了问题:想当然认为word boundary只包括上面的1,2和空格" ",其实
A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".
Exactly which characters are word characters depends on the regex flavor you're working with. In most flavors, characters that are matched by the short-hand character class \w are the characters that are treated as word characters by word boundaries.
当我在class为"account__item--active"的元素中查找"account__item"时函数返回true,然后程序悄悄在这里就出现了问题。这并不是我想要的。后来看了jquery1.10和2.0.3它的主要逻辑是这样实现的:
1 function hasClass(element, cls) { 2 var className = " " + cls + " ", 3 rclass = /[\t\n\r\f]/g; 4 if (element.nodeType === 1 5 && (" " + element.className + " ").replace(rclass, " ").indexOf(className) >= 0) { 6 return true; 7 } // end if 8 return false; 9 } // end hasClass()