什么是jQuery valHooks? [英] What are jQuery valHooks?
问题描述
在 jQuery缺陷中阅读了关于valHooks
的内容之后,最近在小提琴我搜索了jQuery文档和Google,但除了 jQuery 1.6版本发布.请有人可以解释valHooks
是什么以及为什么有用吗?
After reading about valHooks
in a jQuery defect and more recently seen in a fiddle I searched the jQuery documentation and Google but I can't find anything other than a short example in the jQuery 1.6 release post. Please can someone explain what valHooks
are and why they are useful?
推荐答案
这是一组定义如何从DOM元素获取/设置值的函数.
It is a set of functions that define how to get/set values from DOM elements.
并非所有元素都可以使用.value
进行设置.例如,select
元素需要与select.options[select.selectedIndex].value
相似的东西.
Not all elements can be set using .value
. For example, a select
element requires something along the lines of select.options[select.selectedIndex].value
.
底层代码显示例如如何获取/设置select
元素的值:
The underlying code reveals e.g. how to get/set a select
element's value:
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;
}
}
这篇关于什么是jQuery valHooks?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!