jQuery源码解读之hasClass()方法分析


本文较为详细的分析了jQuery源码解读之hasClass()方法。分享给大家供大家参考。具体分析如下:

复制代码 代码如下:
jQuery.fn.extend({
    hasClass: function( selector ) {
//将要检查的类名selector赋值给className, l为选择器选择的当前要检查的jQuery对象数组的长度。
        var className = " " + selector + " ",
            i = 0,
            l = this.length;
//循环检查每一个DOM元素的类名
        for ( ; i < l; i++ ) {
//this[i].nodeType === 1,判断当前DOM节点的节点类型,1表示元素节点。
//this[i].className,获取当前DOM节点已经存在的类名。
//rclass = /[\t\r\n\f]/g,replace(rclass, " ")表示移除当前DOM节点类名里的制表符,换行符,回车符等。
//indexOf(className),开始在当前DOM节点的类名里检索是否有你要检查的类名className,如果>=0,表示存在,返回true,跳出函数。
            if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
                return true;
            }
        }
//循环检查完了,发现每一个DOM元素里都没有找到你要检查的类名,则返回false,跳出函数。
//可见,只要你的jQuery对象数组里,发现有一个DOM元素的类名里包含你要查找的类名,则返回true,跳出函数。
        return false;
    }
});

希望本文所述对大家的jQuery程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3