存储数据
使用data方法可以避免在DOM中存储数据,有些前端开发er喜欢使用HTML的属性来存储数据:
$(
'
selector
'
).attr(
'
alt
'
,
'
data being stored
'
);
// 之后可以这样读取数据:
$( ' selector ' ).attr( ' alt ' );
// 之后可以这样读取数据:
$( ' selector ' ).attr( ' alt ' );
使用”alt”属性来作为参数名存储数据其实对于HTML来说是不符合语义的,我们可以使用jQuery的data方法来为页面中的某个元素存储数据
$(
'
selector
'
).data(
'
参数名
'
,
'
要存储的数据
');
//
之后这样取得数据:
$( ' selector ' ).data( ' 参数 ' );
$( ' selector ' ).data( ' 参数 ' );
这个data方法能让你自己明明数据的参数,更语义更灵活,你可以在页面上的任何元素存储数据信息。如果想了解更多关于data()和removeData()方法的介绍,可以看看jQuery官方讲解。
这个方法的经典应用是给input域一个默认值,然后在聚焦的时候清空它:
HTML部分:
<
form
id
="testform"
>
<
input
type
="text"
class
="clear"
value
="Always cleared"
/>
< input type ="text" class ="clear once" value ="Cleared only once" />
< input type ="text" value ="Normal text" />
</ form >
< input type ="text" class ="clear once" value ="Cleared only once" />
< input type ="text" value ="Normal text" />
</ form >
JavaSript部分:
$(
function() {
//
取出有clear类的input域
// (注: "clear once" 是两个class clear 和 once)
$( ' #testform input.clear ' ).each( function (){
// 使用data方法存储数据
$( this ).data( " txt " , $.trim($( this ).val()) );
}).focus( function (){
// 获得焦点时判断域内的值是否和默认值相同,如果相同则清空
if ( $.trim($( this ).val()) === $( this ).data( " txt " ) ) {
$( this ).val( "" );
}
}).blur( function (){
// 为有class clear的域添加blur时间来恢复默认值
// 但如果class是once则忽略
if ( $.trim($( this ).val()) === "" && ! $( this ).hasClass( " once " ) ) {
// Restore saved data
$( this ).val( $( this ).data( " txt " ) );
}
});
});
// (注: "clear once" 是两个class clear 和 once)
$( ' #testform input.clear ' ).each( function (){
// 使用data方法存储数据
$( this ).data( " txt " , $.trim($( this ).val()) );
}).focus( function (){
// 获得焦点时判断域内的值是否和默认值相同,如果相同则清空
if ( $.trim($( this ).val()) === $( this ).data( " txt " ) ) {
$( this ).val( "" );
}
}).blur( function (){
// 为有class clear的域添加blur时间来恢复默认值
// 但如果class是once则忽略
if ( $.trim($( this ).val()) === "" && ! $( this ).hasClass( " once " ) ) {
// Restore saved data
$( this ).val( $( this ).data( " txt " ) );
}
});
});