Reputation: 22040
$('#A').click(function () {
$('#A1').prepend('<div class="AcL" id=' + i + '>Hello<span class="RmMe" id="' + i + '" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').click(function () {
alert("OK");
});
<div id="A1"></div>
Any idea why the click is not working?
Upvotes: 0
Views: 97
Reputation: 7536
You have to use
$('.RmMe').on("click",function(){
alert("OK");
});
because this element does not exist when your DOM is created, it is inserted afterwards and you cannot bind click to the element which does not exist. .live adds an event listener for you, which makes it easy to achieve the task you want.
Upvotes: 1
Reputation: 6780
You need to use .delegate()
or .live()
because you are attempting to bind a handler to an element that does not yet exist.
$('#A').click(function() {
$('#A1').prepend('<div class="AcL" id='+i+'>Hello<span class="RmMe" id="'+i+'" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').live('click', function() { alert( 'OK' ); });
Try that.
EDIT:
However, should you be using jQuery 1.7+, the .on
method is the preferred approach: See post from xdazz
$('.RmMe').on('click', function () {
alert("OK");
});
Good luck!
Upvotes: 9