jQuery val()方法源碼解讀

來源:互聯網
上載者:User

標籤:

    val: function( value ) {        var hooks, ret, isFunction,            elem = this[0];        if ( !arguments.length ) {//無參數            if ( elem ) {//第一個元素                //考慮元素是checkbox,radio,option或者select的情況,這時有val鉤子                hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];                //如果鉤子存在且有get 且擷取的值不為undefined,返回該值                if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {                    return ret;                }                //否則,ret就是元素的value                ret = elem.value;                //如果值是字串                return typeof ret === "string" ?                    //將分行符號替換為""                    ret.replace(rreturn, "") :                    // 如果值不是字串,考慮null和undefined的情況,如果是null或undefined,ret置為""                    ret == null ? "" : ret;            }            return;        }        //判斷傳入的參數value是否是函數        isFunction = jQuery.isFunction( value );        //遍曆設值        return this.each(function( i ) {            var val;            if ( this.nodeType !== 1 ) {//如果不是元素節點,返回                return;            }            if ( isFunction ) {//如果是函數 函數的參數第一個是索引,第二個是對應的值                val = value.call( this, i, jQuery( this ).val() );            } else {                val = value;            }            //如果val是null或者undefined,設為""            if ( val == null ) {                val = "";            //如果val是數字,轉為字串            } else if ( typeof val === "number" ) {                val += "";            //如果val是數組                } else if ( jQuery.isArray( val ) ) {//處理數組中的undefined null 和數字                val = jQuery.map( val, function( value ) {                    return value == null ? "" : value + "";                });            }            //同樣地,考慮元素是checkbox,radio,option或者select的情況            hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];            // 如果set返回了undefined,回退到正常值val            if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {                this.value = val;            }        });    }

valHooks to be continue

jQuery val()方法源碼解讀

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.