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?
Basically jQuery holds the information you store/retrieve with data(name, value)/data(name) and remove with removeData(name) in an internal javascript object named cache . The rest is just a bit of javascript magic to make it work and keep all the associations right. Oh and to answer the first part of your question.
The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.
version added: 1.4. 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 .
You could use an id attribute like "clicker-123" then parse out the number. I usually do that or use the 'rel' attribute.
So, in essence, there is no better way to do it that I know of. I hope this thread proves me wrong.
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