Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
891 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...