简体   繁体   中英

jQuery click not working for a second time clicked

I am using the following code to send the ajax, but the problem is when user clicks for a second time on the button it does not post to backend or do not submit data, for it to work again the user needs to reload the page again. Anyone has an idea why?

$(document).ready(function () {
    $('#btn_follow').click(function (e) {
        e.preventDefault();
        //e.stopPropagation();
        //$('#divId :input').serialize();
        var follow_and_unfollow = $("#user_page_follow :input").serialize();
        $.post(
            "backend/ajax/follow_and_unfollow.php",
            follow_and_unfollow
        ).done(function (data) {

            //$("#testimonials").load(location.href+" #testimonials>*","");
            $("#follow").html(data);
            $("#user_followers").load(location.href + " #user_followers>*", "");

        }).fail(function () {
            //alert("Error submitting forms!");
        });
    });
});

on second click on #btn_follow it's not submitting, the user needs to reload the page for it to work

As we've confirmed in the comments, you're overwriting your original button with new content returned via AJAX. As such, the button element that you'd bound the click even too is gone, replaced with a new bit of HTML from the server.

I'd suggest you do the following. Replace:

$('#btn_follow').click(function (e) {

With:

$('#follow').on('click', '#btn_follow', function (e) {

This essentially binds the handler to the #follow element, but only runs it if the element clicked matches the filter expression. It's called event delegation and it's an important concept. Read about it here .

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