jQuery的date数据存储

来源:互联网 发布:知名网红淘宝店有哪些 编辑:程序博客网 时间:2024/05/17 01:52
INTRO: 介绍了一下jQuery的date数据存储,使用date()在元素上保存数据可以提升jq的代码效率。

 

对于jQuery的数据存储,初学的时候我们大概会这样写:

12
$('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 代码:

1234567
$("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 代码:

12345
<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 代码:

1234567891011121314151617181920
$(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") );        }    });});

查看Demo

一些注意事项:

1)对应的清除date数据的方法是removeData(name)。在一些AJAX应用中,由于页面刷新很少,对象将一直存在,随着你对data的不断操作,很有可能因为使用不当,使得这个对象不断变大,最终影响程序性能。所以应该及时清理这个对象。

2)对元素执行remove()或empty()操作时,jQuery会帮我们清除元素上的date数据。

3)使用clone()复制元素时,不会将元素上的date数据一起复制。

或许您对这些文章也感兴趣:

  • 2010年10月8日 -- 近期jQuery学习的一些心得
  • 2010年09月27日 -- 发布一个仿Fotolog的jQuery相册效果|ks-fotolog V1.0
  • 2010年09月3日 -- [翻译]jQuery|你应该尽早知道的7条技巧
  • 2010年08月19日 -- 主流JavaScript框架的浏览器检测
  • 2010年08月4日 -- [转]JQuery事件参数传递
  • 2010年05月11日 -- [js学习]密码提示强度
原创粉丝点击