简体   繁体   中英

click event on dynamic li elements

Updated the question as per @Jonathan Kuhn's feedback and it works like a charm

I am building a messaging system for my web application.

where the users should be able to communicate with me via messages (ajax)

I am being able to append <ul> with additional <li> from jQuery

$('#send').click(function(e){
            e.preventDefault();
            var reply = $('#reply').val();

            var project_id = 44; // just for reference
            $.ajax({
                type: "post",
                url: "<?php echo base_url(); ?>messages/send",
                data:{ msg:reply, project_id:project_id },
                success: function (response) {


                    if(response=="success"){

                        $(".messages").append('<li class="message" id="message">'+reply+'<a id="delete">delete</a></li>');
                        var clearText = "ture";

                    }else{

                    }

                }


            });

Which is working perfectly fine. But I am having problem while deleting the dynamically added list element.

I tried bind() and on() jQuery functions but as I am not much good at it, I am facing a lot of issues.

$("#messages").on('click', '#delete', function(event) {
                event.preventDefault();
                var id = 22 ; // just for reference
                $.post( "<?php echo base_url(); ?>messages/delete", { type:'single', id:id } )
                  .done(function( data ) {


                });
                $(this).closest('li').remove();
            });

My HTML structure is as below

<ul class="messages" id="messages">
        <li class="message" id="message">sdaghds<a id="delete">delete</a></li>
    </ul>

You have id="#messages" on the <ul> . Remove the # and then the .on one should work.

Also, ids are supposed to be unique throughout the page. So you shouldn't have multiple message ids throughout. If you need multiple, use classes. Remove the id from the <li> .

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