jquery - 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');
});
解决方案
因为创建 click 事件处理程序时 DOM 中不存在该元素,所以它找不到该元素。相反,您可以从下面委托事件body
:
$('body').on('click', '.close', function(){
$(this).parents('.pulled_in_html');
});
事件委托允许您避免将事件侦听器添加到特定节点;相反,事件侦听器被添加到一个父级。该事件侦听器分析冒泡事件以查找子元素的匹配项。
您可以在此处阅读有关事件委托的更多信息
您的代码似乎没有尝试隐藏任何内容,我不知道您是否故意将其遗漏,但要隐藏元素,您可以将hide()
方法链接到此行:
$(this).parents('.pulled_in_html').hide();
推荐阅读
- python - 多处理 Python 无法更新 O(1) 中的字典列表
- continuous-integration - GitLab 自定义 CI 配置路径和合并请求
- symfony - 多对多和新实体的学说并发
- django - 是否可以暂停 django 后台任务?
- android - 如何解决 http 和站点行为:android 应用程序中的导航错误?
- javascript - 我如何在不打开任何东西的情况下使用服务器?
- pandas - 使用条件对数据框中的项目进行分组
- java - 回收站视图不显示任何项目
- r - 如何在我的 R 包中将函数导出为 S3 方法?
- reactjs - 使用和 react-hook-form 进行 React yup 验证,不同类型对象的数组取决于对象属性之一