I have some javascript/jquery code that dynamically populates an unordered list with a bunch of list items. In the list items I have a link and I want to associate some data with that link which is generated like so:
var thing1 = { name: 'My Object' };
var thing2 = { name: 'My Other Object' };
var li = $('<li></li><br />');
var aSel = $('<strong>' + thing1.name + '<br /><a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>';
li.append(aSel);
li.append(add);
$('#sidebar').append(li);
//This is in a loop so the same thing would happen with thing2, etc
would generate HTML like so:
<div id="results">
<ul id="sidebar">
<li>
<strong>My Object</strong><br />
<a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>
</li>
<li>
<strong>My Other Object</strong><br />
<a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>
</li>
</ul>
</div>
So if the user clicks the first Add Deal link, I want to work with the thing1 data elsewhere in my script. If they second link is clicked on, I want to work with the thing2 data.
The path I’m going down involves an array and some code that doesn’t feel quite right to me. I figure I’m missing something trivial.
You can use the jQuery.data function to attach a “thing” to each of your links. Right after the
var aSel =line:Then when the anchor tag is clicked, retrieve it with:
var thing = $(this).data('thing');