【问题标题】:AJAX success html dialog, won't close on button clickAJAX 成功 html 对话框,不会在按钮单击时关闭
【发布时间】:2019-03-29 10:09:52
【问题描述】:

所以我提出了一个 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');
    });

【问题讨论】:

  • 要为您指明正确的方向,就像@matt 所做的那样,为您的事件侦听器使用“on”。当您使用 click 事件侦听器时,您会将其附加到现有元素,因此当您加载 javascript 时,您会尝试将事件侦听器附加到尚不存在的元素,而他的 $('body').on('click', '.close', ...) 将附加现有 body 元素的事件监听器,监听 body 元素内的所有点击,并触发任何具有“close”类的子元素。
  • 明白。那么你将如何解决这个问题?

标签: jquery html ajax


【解决方案1】:

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

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

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

你可以阅读更多关于事件委托here

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

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

【讨论】:

  • 绝对不应该,你还有什么活动?
  • 我已将其全部添加到 JSFiddle 中。见这里:jsfiddle.net/9h21rxtu
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多