简体   繁体   中英

Jquery on('click') not firing after first click

I have some HTML:

<div class="post-container self">
    <a href="/user/Wiz">
        <img class="avatar" alt="Profile Picture" src="">
    </a>
    <div class="post-body">
        <div class="post" style="margin-left:0px;">
            <div class="post-timestamp" style="display:inline-block;float:right">
                <a href="/posts/80" style="color:#999">Oct 31</a>
            </div>
            <div class="post-functions dropdown displaynone" style="float:right;margin-right:5px;">
                <a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
                    <i class="icon-cog"> 
                    </i>
                </a>
                <ul class="dropdown-menu post-dropdown" role="menu" aria-labelledby="dLabel">
                    <a class="post-delete" href="javascript:void(0)"><i class="icon-trash"> </i>Delete</a>
                </ul>
            </div>
        </div>
    </div>
</div>

And with that, I have some Jquery:

$('.posts-content').on('click', '.post-delete', function(e) {
                $('.post-dropdown').dropdown();
                if (confirm('Are you sure you want to delete this post?')) {
                    var $this = $(this);
                    $.ajax({
                        url: '/a/delete_post',
                        type: 'POST',
                        dataType: 'json',
                        data: {'p' : post_id},
                        success: function() {
                            //... 
                            return true;
                        }
                    });
                }
                return false;
            });

Everything works perfectly the first click, but if I go to another post, and try to click .post-delete , the event never fires, and nothing shows up in the console. It also works if I use $.click() , but I need to dynamically create elements. Why does the $.on('click') not fire the second click?

My guess is that dropdown plugin you use change the DOM structure.

$('.post-dropdown').dropdown();

BTW,

$this.parent().parent().parent().parent().parent() this is really really bad practice.
You should use closest instead.

如果要动态创建元素,请尝试:

$(document).on('click', '.post-delete', function(e) { });

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