[jQuery] Covering multiple elements with a single function, but passing a variable?

[jQuery] Covering multiple elements with a single function, but passing a variable?


Hi. I'm stuck trying to figure out the jQuery way to code this
functionality I have in my project.
Below is a stripped down example of what I'm trying to do. When I
click the "Add Item" link below any list, I want to just append a new
element to the end of that list. What I do now is just use an onclick
element for each anchor tag, and call addItem and pass the specific
list_id for that list. The function then dynamically locates that
specific list and appends a new item.
What I have here works (excuse any typos, I'm writing from memory),
but I'd like to make it cleaner by getting rid of the onclick calls
and just having jQuery bind a function to the "additem" class. I just
can't figure out how to pull in the list_id variable in each case.
Any ideas?
...
function addItem(list_id) {
$('#list_'+list_id+' > ul').append('<li>data</li>');
return false;
}
...
<ul id="list_1">
<li>data</li>
<li>data</li>
</ul>
<a class="additem" href="#" onclick="addItem(1);return false;">Add
Item</a>
<ul id="list_2">
<li>data</li>
<li>data</li>
</ul>
<a class="additem" href="#" onclick="addItem(2);return false;">Add
Item</a>
...