在阅读valHooks了jQuery缺陷之后,我最近看到了一个小提琴,我搜索了jQuery文档和Google,但除了jQuery 1.6发布文章中的简短示例之外,我找不到任何其他内容.请有人解释一下valHooks它们有用的原因和原因吗?
Daf*_*aff 15
我在这里做了一个简单的例子.
$.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());
Run Code Online (Sandbox Code Playgroud)
pim*_*vdb 14
它是一组函数,用于定义如何从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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9176 次 |
| 最近记录: |