I am having problem with jQuery, which I recently starting playing around with. I will try to explain my situation as well as I can and try to add all relevant information.
What I want:
Two lists, one in its own tab. Each item in the list has two images which also act as buttons. When a button is pressed, an event occurs. The event would be adding element to the other list. For now, as a proof of concept, this event is an alert containing the id of the list item.
The problem:
The alert occurs at an increasing rate, each time the button is pressed. More precisely, after every time pressing the button, one more alert pops up than before. The first time, nothing happens. The next time one alert is shown. After that two sequential alerts are shown, etc.
It is not obvious to me why this happens. I would appreciate if someone can point out to me what I might be doing wrong.
HTML:
<div class="demo">
<div id="tabs">
<ul>
<li><a href="#tabs-1">Tab 1</a></li>
<li><a href="#tabs-2">Tab 2</a></li>
</ul>
<div id="tabs-1">
<ul id="sortable11" class="todoList">
<li id="6" class="todo">
<div class="text">This is text (6)</div>
<div class="actions">
<a href="#" class="edit">Edit</a>
<a href="#" class="delete">Delete</a>
</div>
</li>
</ul>
</div>
<div id="tabs-2">
<ul id="sortable22" class="todoList">
<li class="ui-state-highlight">Item 1</li>
<li class="ui-state-highlight">Item 2</li>
</ul>
</div>
</div>
</div>
CSS:
.todo .actions a.edit{
background:url("../img/edit.png") no-repeat center center;
}
.todo .actions a.delete{
background:url("../img/delete.png") no-repeat center center;
}
jQuery:
$('.todo a.edit').live('click',function(){
$('#sortable11 > li').click(function(){
var current_id = $(this).attr("id");
alert(current_id);
});
});
You’re binding the click in other click handler and it’s plain wrong.
Just bind it once and it will work fine:
In jQuery, binding event handler is not overriding existing handlers, but is adding new handler to allow more flexible programming.
You can remove the previously attached handlers, but I can’t see any reason to do that.