什么是jQuery valHooks?
在阅读了jQuery缺陷中的 valHooks
,我最近在一个小提琴中看到了我搜索jQuery文档和Google,但除了jQuery 1.6发布文章中的简短示例之外我找不到任何其他内容。 请有人解释一下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; } }
我在这里做了一个简单的例子。
$.valHooks['myedit'] = { get : function(el) { return $(el).html(); }, set : function(el, val) { $(el).html(val); } }; $.fn.myedit = function() { this.each(function() { this.type = 'myedit'; }); return this; } $('#edit').myedit().val(' Hi there!'); $('#value').html('The value is : ' + $('#edit').val());
valHooks允许您覆盖任何jQuery可访问对象的.val()
的默认行为。