Reputation: 25525
I have an ordered list, and each item has a link with class "additem" to add another item to the list. In order to make the add item links in the newly added items work, I used .live(), like this:
function pageFunctions() {
$('a.additem').click(function() {
$('<li>'+trackli+'</li>').insertAfter($(this).parent());
});
});
// there are other functions that warrant 'pageFunctions' being a separate function
$(function() {
pageFunctions();
$('a.additem').live('click', pageFunctions);
});
However, what happens is that the first time you click the add item link, it works fine. But after that, instead of adding an item once, it will double it. and the third time double it again. Any ideas how to fix this?
Upvotes: 1
Views: 54
Reputation: 19636
What's happening here is that whenever you click 'a.additem' you are binding a new click event to the anchor each time, as well as creating the list element. This means every time you click the anchor, the code is going to run twice as many times as the previous execution.
The following should work:
function pageFunctions() {
$('<li>'+trackli+'</li>').insertAfter($(this).parent());
});
$(function() {
$('a.additem').live('click', pageFunctions);
});
Upvotes: 0
Reputation: 2087
The problem is that you're registering additional new event handlers via the .click() call every time pageFunctions is getting called. Try this instead:
function pageFunctions() {
$('<li>'+trackli+'</li>').insertAfter($(this).parent());
});
$(function() {
pageFunctions();
$('a.additem').live('click', pageFunctions);
});
Upvotes: 1
Reputation: 7254
Your binding a click event to 'a.additem'
each time you run pageFunctions. Remove the binding from the pageFunctions function and your problem should go away.
Upvotes: 0