jQuery data()函数做什么 [英] what does jQuery data() function do

查看:91
本文介绍了jQuery data()函数做什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有找到jquery函数data()的用途. 谁能给我一些如何使用它的例子?

I have not found what is the use of jquery function data(). Can anyone give me some example of how it can be used?

推荐答案

它对于将各种对象,字符串,数组等与DOM元素相关联非常有用.假设有一个有趣的用法:

Its really useful for associating various objects, strings, arrays, etc with a DOM element. Here is a fun hypothetical use:

$(document).ready(function(){
   $("a").each(function(index, el){
      if(index % 2 == 0) 
         $(this).data('coolColor', 'Orange'); // Set the data
      else 
         $(this).data('coolColor', 'Purple'); // Set the data
   }).click(function(e){
      alert($(this).data('coolColor')); // Retrieve the data
      e.preventDefault();
   });
});

这将选择每个a标记,并将Orange设置为奇数,将Purple设置为偶数.如果您确实想这样做,这不是编写此代码的最佳方法,但是它确实说明了如何使用.data()函数.

This would select every a tag, and set Orange if its odd, or Purple if its even. This is not the most optimal way to write this code if this is what you really wanted to do, but it does illustrate how to use the .data() function.

您还可以使用它来存储对象:

You can also use it to store objects:

$("#header").data('headerSettings',{
   color: "red",
   cost:  "$25.00",
   time:  1000
});

现在您可以在页面上的其他任何地方访问该数据:

Now you could access that data anywhere else on the page:

$("#header").data('headerSettings').color;

这篇关于jQuery data()函数做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆