首页 > 解决方案 > AJAX 成功 html 对话框,不会在按钮单击时关闭

问题描述

所以我提出了一个 AJAX 请求,它提交正常并按预期返回成功的 HTML - 但在返回到目标 div 元素的 HTML 中,它有一个按钮。我在其中添加了 jQuery,当它被点击时,它会隐藏 HTML 以防止 AJAX 成功。

简而言之:我希望关闭按钮关闭 div,但它似乎不起作用。

$('#user_report__dd #make_report').click(function(){
        var interaction_type = $(this).data('interaction_type');
        var user_id = $(this).data('user_id');
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: ajax_url,
            data: {
                interaction_type: interaction_type,
                user_id: user_id,
            },
            success:function(html){
                // $('.ajax_call').html(html);
                $('.ajax_call').html(html);
                // stop body from scrolling
            }
        });
    });
if(isset($_POST['interaction_type']) && $_POST['interaction_type'] == 'report_user'){
    global $report;
    $report->Form($_POST['user_id'], 'user');
    // This returns the HTML
}

然后在我的主 jQuery 文件中

$('.close').click(function(){
        $(this).parents('.pulled_in_html');
    });

标签: jqueryhtmlajax

解决方案


因为创建 click 事件处理程序时 DOM 中不存在该元素,所以它找不到该元素。相反,您可以从下面委托事件body

$('body').on('click', '.close', function(){
    $(this).parents('.pulled_in_html');
});

事件委托允许您避免将事件侦听器添加到特定节点;相反,事件侦听器被添加到一个父级。该事件侦听器分析冒泡事件以查找子元素的匹配项。

您可以在此处阅读有关事件委托的更多信息

您的代码似乎没有尝试隐藏任何内容,我不知道您是否故意将其遗漏,但要隐藏元素,您可以将hide()方法链接到此行:

    $(this).parents('.pulled_in_html').hide();

推荐阅读