Add a close event button to every <li> in an <ul>
I would like to add an x button to every <li> I have in my <u开发者_开发技巧l>. This x (close) button will delete that individual <li> from the <ul>. How do I do this using jQuery to create a single function that takes the this to delete the current item?
Heres my example HTML:
<ul id="list_a">
<li value="1">Red <span class="closeButton">X</span></li>
<li value="2">Orange <span class="closeButton">X</span></li>
<li value="3">Green <span class="closeButton">X</span></li>
</ul>
edit: added close button <span>
// Use live to bind click event to each element with closeButton class and remove it
$('.closeButton').live('click', function(){
$(this).parent().remove();
});
<ul id="list_a">
<li value="1">Red <span class="closeButton">X</span></li>
<li value="2">Orange <span class="closeButton">X</span></li>
<li value="3">Green <span class="closeButton">X</span></li>
</ul>
jsFiddle
Event delegation. Select the list, then ask it to listen to click events on the .closeButtons. Then remove the li or the parent of the span.
$("#list_a").delegate(".closeButton", "click", function() {
$(this).parent().remove();
});
I would also create the close Buttons dynamically with jQuery.
$('#list_a li').each(function(){
$(this).append($('<span/>',{html:'X',class:'closeButton'}).click(function(){
$(this).parent().remove();
}));
});
加载中,请稍侯......
精彩评论