简体   繁体   中英

Button to remove a dynamically created list element using JQuery

I have an ordered list in HTML:

<ol id ="list">
</ol>

which gets added to using JQuery/javascript:

$(function (){
    $("#click-me").click(function (e){
        e.preventDefault();
        i++;

        var list = $("#list");
        var name = $("#colleague-select option:selected").text();
        var remove = "<button type='button' class='remove-me'> X </button>";
        var entry = "<li>" + name + remove+ "</li>";
        entry.id = "entryid" + i;

        list.append(entry);

        return false;
    });
});

What I'm trying to do is to allow a user to remove an entry in the list by clicking its corresponding button "X" . This is the code I've come up with, but it's not working:

$(function (){
   $(".remove-me").click(function(e){

       var list = $("#list");
       var entry = e.parent(); //find parent entry of clicked "X" button
       list.remove(entry);  //remove entry from list
   });
});

Any help guys? I am fairly new to JQuery so an explanation of your answer code would be much appreciated. Thanks.

You need to use event delegation for binding events to dynamically added elements.

$(document).on('click', ".remove-me", function(e){
    var entry = $(this).parent(); 
    entry.remove();  //remove entry from list
});

just remove the parent element

$(function (){
   $(document).on("click", ".remove-me", function(e){
       $(this).parent().remove(); //find parent entry of clicked "X" button
   });
});

A foolproof way is add the event to the button

<button type='button' onclick='removeMe(this);' class='remove-me'> X </button>

and on js

function removeMe(e)
{
   $(e).parent().remove();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM