In a previous life, I might have done something like this:
<a href='#' onclick='f(311);return false;'>Click</a><br/> <a href='#' onclick='f(412);return false;'>Click</a><br/> <a href='#' onclick='f(583);return false;'>Click</a><br/> <a href='#' onclick='f(624);return false;'>Click</a><br/>
Now with jQuery, I might do something like this:
<a class='clicker' alt='311'>Click</a><br/> <a class='clicker' alt='412'>Click</a><br/> <a class='clicker' alt='583'>Click</a><br/> <a class='clicker' alt='624'>Click</a><br/> <script language='javascript' type='text/javascript'> $('.clicker').bind('click', function(e) { e.preventDefault(); f($(this).attr('alt')); }); </script>
Except that using the alt attribute to pass the data from the DOM to jQuery feels like a hack, since that’s not its intended purpose. What’s the best practice here for storing/hiding data in the DOM for jQuery to access?
JQuery.data lets you associate a dictionary to a DOM element. This data can be set via jQuery:
or (since jQuery 1.4.3) using the HTML5 data- attributes, which work even in non-HTML5 documents: