The jQuery .data() documentation says the following:
The .data() method allows us to attach data of any type to DOM element
I assume "any type" refers to functions as well. Say I have a div with the id foo as such:
<div id="foo">Foo!</div>
And I'd like to store a function in it called say
that takes a parameter. According to the documentation I'd store the function this way:
$("#foo").data("say", function(message){ alert("Foo says "+message); });
My question is, how do I invoke the function with a parameter when I wish to do so.
$("#foo").data("say");
should return the function, but how would I pass a parameter to it?
Thanks!
The . data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr .
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.
It should be noted that jQuery's data() doesn't change the data attribute in HTML. So, if you need to change the data attribute in HTML, you should use . attr() instead.
A better alternative to storing functions in data
is using custom events. This can be done easily with on
and trigger
:
$('#foo').on('say', function(e, arg){ alert('Foo says ' + arg); }); $('#foo').trigger('say', 'hello');
Example: http://jsfiddle.net/tW66j/
Note: on earlier versions of jQuery (until 1.7), .bind
was used instead of .on
.
var myFunction = $("#foo").data("say"); myFunction(someParameter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With