I need to trigger click events of “a” tags which are in “deletable” class. I saw some similar question in SO, but following code doesn’t work for me. What i’m trying to do is to delete relevant <li> from <ul>.
$(document).ready(function () {
$('.deletable').live("click", function () {
alert("test"); // Debug
// Code to remove this <li> from <ul>
});
});
<form ...>
<ul>
<li>One<a href="#" class="deletable">Delete</a></li>
<li>Two<a href="#" class="deletable">Delete</a></li>
<li>Three<a href="#" class="deletable">Delete</a></li>
</ul>
</form>
I assume i’m using incorrect object hierarchy inside $('...') tag. But i don’t have enough js/jquery/DOM knowladge to solve this problem. please help.
EDIT
Thanks for the answers, but none of them works for me. Actually i’m adding <li>s dynamically. There maybe a problem. Please check,
#sps – a listbox
#add – a button
#splist – another listbox
#remove – a button
$(document).ready(function() {
$('#add').click(function(e) {
var selectedOpts = $('#sps option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#splist').append($(selectedOpts).clone());
$('ul').append('<li>' + selectedOpts.text() + '<a href="#" class="deletable" id="id' + selectedOpts.val() + '">Remove</a>' + '</li>');
e.preventDefault();
});
$('#remove').click(function(e) {
var selectedOpts = $('#splist option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$(selectedOpts).remove();
e.preventDefault();
});
});
The
.live()method of jQuery has been deprecated. You can get similar functionality using$('body')and delegating to.deletablelike I did in the following code:The preventDefault method is used to keep the link from loading a new page should there be something targeted in the href attribute. If you keep the same HTML structure as you have in your example, then you can simply take the anchor element (
this) and grab the parent, then remove it from the DOM.It would be wise to, instead of using
$('body'), target the container for the .deletable anchors, which, in this case, would be$('ul'). The function would look like this:Using
$('body')means that every event on the page would have to be filtered to see if it originated from a .deletable anchor. By scoping it to theulpreceding your li’s, you limit the number of times your function is called increasing performance.