I have not found what is the use of jquery function data().
Can anyone give me some example of how it can be used?
views:
130answers:
4The 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.
It allows you to associate any type of data with a DOM element. See this blog post for some examples.
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); });
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;