Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associating data to a DOM element for jQuery

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?

like image 320
Soldarnal Avatar asked Dec 12 '08 22:12

Soldarnal


People also ask

How have you stored and referenced data in your jQuery code?

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.

What is DOM element in jQuery?

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.

What does .data do in jQuery?

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 .


1 Answers

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.

like image 165
John Sheehan Avatar answered Sep 29 '22 17:09

John Sheehan