Reputation: 133
I'm trying to add an on click event to an <a> element inside a <li>.
When the page is loaded the event is added fine but when I add it dynamically another <a> (pressing a button) it isn't working.
I read that the problem is because the event is handled and not delegated.
What do I have to change in my function to get the event delegated?
Also I need that the added <a> has the class "deleteAttachment".
Here is the snippet:
$(document).ready(function(){
var a = 0;
$('button[data-button="attachment"]').on("click",function () {
var ul = $(this).next("ul");
var li = ul.find("li:last-child");
var element ="<li name='li3'>";
element += '<a class="deleteAttachment">' + a + '</a></li>';
li.before(element);
a++;
});
$('li').on("click", 'a.deleteAttachment', function () {
alert("click");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div>
<button name="Button1" data-button="attachment">
button1
</button>
<ul name="ulbuton1">
<li name="li3">
<a class="deleteAttachment">a</a>
</li>
</ul>
<button name="Button2" data-button="attachment">
button2
</button>
<ul name="ulbuton2">
<li name="li3">
<a class="deleteAttachment">b</a>
</li>
</ul>
<button name="Button3" data-button="attachment">
button3
</button>
<ul name="ulbuton3">
<li name="li3">
<a class="deleteAttachment">c</a>
</li>
</ul>
</div>
</body>
</html>
Upvotes: 2
Views: 1034
Reputation: 11480
I think this is a good solution to your question:
$( "body" ).delegate( "a.deleteAttachment", "click", function() {
//do your stuff here
});
Upvotes: 0
Reputation: 1945
Event delegation means that you add the event handler to a parent rather than to its children so that, irrespective of the number of children that need to handle a certain kind of event, you will have only one handler (at the parent) for that event.
Actually, the event keeps on bubbling up until it finds a handler that catches it eventually. So you can place it anywhere "above" your element (in principle).
In your case, you are attaching the event to the li
, which is supposed to be a child in this case.
You need to attach the event to its parent, which should exist already, so that when the event is triggered on the li
, it is bubbled up to the parent, caught and executed.
Attach it to the ul
, div
or the body
.
Upvotes: 1
Reputation: 318302
You're adding the LI as well, so delegating to that won't work, you have to delegate to something that is actually there, like the UL
$('ul').on("click", 'li a.deleteAttachment', function () {
alert("click");
});
Upvotes: 4