您的位置:首页 > Web前端 > JavaScript

javascript 如何判断元素是否包含一个特定的类,hasClass函数的实现

2013-12-13 07:36 866 查看
刚开始这么写的:

function hasClass(element, cls) {
var regexp = new RegExp("\\b" + cls + "\\b");
return element.className.search(regexp) !== -1;
} // 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它的主要逻辑是这样实现的:

function hasClass(element, cls) {
var className = " " + cls + " ",
rclass = /[\t\n\r\f]/g;
if (element.nodeType === 1
&& (" " + element.className + " ").replace(rclass, " ").indexOf(className) >= 0) {
return true;
} // end if
return false;
} // end hasClass()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐