对于jQuery的数据存储,初学的时候我们大概会这样写:
1 2 | $('selector').attr('alt', 'data being stored');
$('selector').attr('alt'); // 之后这样读取。 |
使用”alt”属性来作为参数名存储数据其实对于HTML来说是不符合语义的,这也给html增加了额外的负担。同样道理,用类似于”attr”、”original”等属性也是一样。
其实我们可以使用jQuery的data方法来为页面中的某个元素存储数据。
官方文档中这样描述:
data(name,value):
Stores the value in the named spot and also returns the value.
This function can be useful for attaching data to elements without having to create a new expando. It also isn’t limited to a string. The value can be any format.
date(name):
Returns value at named data store for the element, as set by data(name, value).
This function is used to get stored data on an element without the risk of a circular reference. It uses jQuery.data and is new to version 1.2.3. It can be used for many reasons and jQuery UI uses it heavily.
实例,在一个元素上存取数据。
HTML 代码:
1 | <div></div> |
jQuery 代码:
1 2 3 4 5 6 7 | $("div").data("blah"); // undefined
$("div").data("blah", "hello"); // blah设置为hello
$("div").data("blah"); // hello
$("div").data("blah", 86); // 设置为86
$("div").data("blah"); // 86
$("div").removeData("blah"); // 移除blah
$("div").data("blah"); // undefined |
文档里解释的“使用date在元素上存储数据能够避免循环引用的风险”暂时还没明白什么意思,记一下。
这个方法的经典应用是给input域一个默认值,然后在聚焦的时候清空它:
HTML 代码:
1 2 3 4 5 | <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> |
jQuery 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $(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") );
}
});
}); |
一些注意事项:
1)对应的清除date数据的方法是removeData(name)。在一些AJAX应用中,由于页面刷新很少,对象将一直存在,随着你对data的不断操作,很有可能因为使用不当,使得这个对象不断变大,最终影响程序性能。所以应该及时清理这个对象。
2)对元素执行remove()或empty()操作时,jQuery会帮我们清除元素上的date数据。
3)使用clone()复制元素时,不会将元素上的date数据一起复制。
本文介绍了如何使用jQuery的data方法为页面元素存储数据,包括设置、获取和删除数据的过程,并通过实例展示了其在input域中设置默认值的应用。
111

被折叠的 条评论
为什么被折叠?



