简体   繁体   English

jQuery单击第二次不起作用

[英]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. 我正在使用以下代码发送ajax,但问题是,当用户第二次单击按钮时,它不发布到后端或不提交数据,要使其再次起作用,用户需要再次重新加载页面。 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 在第二次单击#btn_follow它没有提交,用户需要重新加载页面才能正常工作

As we've confirmed in the comments, you're overwriting your original button with new content returned via AJAX. 正如我们在评论中确认的那样,您正在用通过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. 这样,绑定了单击的按钮元素也消失了,取而代之的是服务器中的HTML。

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. 这实际上将处理程序绑定到#follow元素,但仅在所单击的元素与过滤器表达式匹配时才运行该处理程序。 It's called event delegation and it's an important concept. 这称为事件委托,这是一个重要的概念。 Read about it here . 在这里阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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