开发者

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&nbsp;&nbsp;<span class="closeButton">X</span></li>
  <li value="2">Orange&nbsp;&nbsp;<span class="closeButton">X</span></li>
  <li value="3">Green&nbsp;&nbsp;<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&nbsp;&nbsp;<span class="closeButton">X</span></li>
   <li value="2">Orange&nbsp;&nbsp;<span class="closeButton">X</span></li>
   <li value="3">Green&nbsp;&nbsp;<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();
    }));
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜