tags:

views:

130

answers:

4

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

A: 

The jQuery documentation sums it up pretty well:

Returns a unique ID for the element.

Typically this function will only be used internally. You will likely not use the data() method in this way. It is called automatically when necessary when using the other data() functionality.

Basically this function exists to support other jQuery functions. It is best to ignore this function as it is not intended to to part of the public interface of the jQuery API.

Andrew Hare
You're referring to `jQuery.data`, while the OP is referring to `jQuery.fn.data` ... Quite different.
J-P
+1  A: 

It allows you to associate any type of data with a DOM element. See this blog post for some examples.

Marek Karbarz
A: 

Returns a unique ID for the element.

Get the store id of an element. It is assigned on the data() function call if one hasn't been assigned yet. $(document.body).click(function(e) { var id = jQuery.data(e.target); $("span").text(id); });

Ashutosh Singh
+1  A: 

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 right 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;
Doug Neiner
I thi8nk it assigns value to variables just likevar color = "orange"
Mirage