什么是jQuery valHooks?

前端之家收集整理的这篇文章主要介绍了什么是jQuery valHooks?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
jQuery defect中阅读了关于valHooks以及最近在 fiddle中看到的更新版本之后,我搜索了jQuery文档和Google,但除了 jQuery 1.6 release post中的一个简短示例之外,我找不到任何东西。请问有人可以解释valHooks是什么,为什么它们有用吗?

解决方法

它是一组定义如何从DOM元素获取/设置值的函数

并非所有元素都可以使用.value进行设置。例如,select元素需要沿着select.options [select.selectedIndex] .value的行。

底层代码显示例如。如何获取/设置select元素的值:

select: {
        get: function( elem ) {
            var value,index = elem.selectedIndex,values = [],options = elem.options,one = elem.type === "select-one";

            // Nothing was selected
            if ( index < 0 ) {
                return null;
            }

            // Loop through all the selected options
            for ( var i = one ? index : 0,max = one ? index + 1 : options.length; i < max; i++ ) {
                var option = options[ i ];

                // Don't return options that are disabled or in a disabled optgroup
                if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
                        (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode,"optgroup" )) ) {

                    // Get the specific value for the option
                    value = jQuery( option ).val();

                    // We don't need an array for one selects
                    if ( one ) {
                        return value;
                    }

                    // Multi-Selects return an array
                    values.push( value );
                }
            }

            // Fixes Bug #2551 -- select.val() broken in IE after form.reset()
            if ( one && !values.length && options.length ) {
                return jQuery( options[ index ] ).val();
            }

            return values;
        },set: function( elem,value ) {
            var values = jQuery.makeArray( value );

            jQuery(elem).find("option").each(function() {
                this.selected = jQuery.inArray( jQuery(this).val(),values ) >= 0;
            });

            if ( !values.length ) {
                elem.selectedIndex = -1;
            }
            return values;
        }
    }
原文链接:https://www.f2er.com/jquery/183301.html

猜你在找的jQuery相关文章