jQuery的属性操作主要包括

  jQuery.fn.val

  jQuery.fn.attr

  jQuery.fn.removeAttr

  jQuery.fn.prop

  jQuery.fn.removeProp

  jQuery.fn.addClass

  jQuery.fn.removeClass

  jQuery.fn.toggleClass

  

  接下来一一分析jQuery对他们的处理

a. jQuery.fn.val


  jQuery.fn.val用来获取jQuery对象的第一个元素的val值或者给jQuery对象的每一个元素设置其val值。参数个数为0表示获取get,否则表示设置set。

  处理过程比较简单:

  判断参数个数,没有参数表示获取当前匹配元素中的第一个元素的value值,此时如果能使用valHooks则使用之,否则使用elem.value获取值(null/undefined需要转成空字符"");

  如果有参数,表示要为当前所有的匹配元素设置值,如果参数是函数,调用函数的返回值作为值val,否则使用传递的参数做为值val。能使用则用之,否则使用elem.value = val。

  源码:

jQuery-1.9.1源码分析系列(八) 属性操作
val: function( value ) {
    var ret, hooks, isFunction,
    elem = this[0];//获取jQuery对象的第一个元素
    //获取值
    if ( !arguments.length ) {
        if ( elem ) {
       hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
            //通过hooks如果能取到值则返回
            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }
            //否则正常取值
            ret = elem.value;
            return typeof ret === "string" ?
                    // 换行符转换成空字符
                    ret.replace(rreturn, "") :
                    //处理null/undef 或数字
                    ret == null ? "" : ret;
        }
        return;
    }

    isFunction = jQuery.isFunction( value );
    //对jQuery对象的每一个元素设置val
    return this.each(function( i ) {
        var val,
        self = jQuery(this);
        //元素不为DOM节点则返回
        if ( this.nodeType !== 1 ) {
            return;
        }

        if ( isFunction ) {
            val = value.call( this, i, self.val() );
        } else {
            val = value;
        }

        //用空字符替换null/undefined;数字转化成字符串
        if ( val == null ) {
            val = "";
        } else if ( typeof val === "number" ) {
            val += "";
        } else if ( jQuery.isArray( val ) ) {
            val = jQuery.map(val, function ( value ) {
                return value == null ? "" : value + "";
            });
        }

        hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

        //如果hooks的set返回为undefined,则使用正常设置
        if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
            this.value = val;
        }
    });
}
View Code

相关文章:

  • 2021-11-29
  • 2021-10-03
  • 2021-10-01
  • 2021-11-15
  • 2021-12-19
  • 2021-12-14
  • 2021-06-29
  • 2021-07-21
猜你喜欢
  • 2021-12-06
  • 2021-08-12
  • 2022-03-02
  • 2021-11-26
  • 2021-07-31
  • 2021-12-08
  • 2022-03-01
相关资源
相似解决方案