jQuery data()函数做了什么

11 jquery jquery-data

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

Dou*_*ner 15

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

$(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();
   });
});
Run Code Online (Sandbox Code Playgroud)

这将选择每个a标签,并设置Orange是否为奇数,或者Purple是否为偶数.如果这是您真正想要的,那么这不是编写此代码的最佳方式,但它确实说明了如何使用该.data()函数.

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

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

现在,您可以在页面上的任何其他位置访问该数据:

$("#header").data('headerSettings').color;
Run Code Online (Sandbox Code Playgroud)