添加jScroll后SweetAlert2失效求助:滚动加载元素无法触发弹窗
问题解决:滚动加载后SweetAlert2弹窗失效
问题原因
你直接用$('.__sweet_edit').on('click', ...)绑定事件时,只会给页面初始加载时已经存在的.__sweet_edit按钮绑定点击事件。而jScroll滚动加载出来的新按钮是后续动态添加到DOM里的,没被绑定这个点击事件,自然触发不了弹窗。
解决方案:用事件委托
修改SweetAlert2的事件绑定代码,把事件委托给一个页面加载时就存在的父元素(比如滚动容器.infinite-scroll,或者直接用document)。这样动态新增的按钮触发点击事件时,会冒泡到父元素被捕获执行。
修改后的代码:
// 把事件委托到document,或者更具体的父元素(比如.infinite-scroll) $(document).on('click', '.__sweet_edit', function(e) { e.preventDefault(); const self = $(this); const placeId = $(this).attr("data-place_id"); const placeName = $(this).attr("data-place_name"); const urlEdit = $(this).attr("data-url_edit"); const dateName = $(this).attr("data-date_name"); const urlDestroy = $(this).attr("data-url_delete"); Swal.fire({ title: placeName, html: `<x-sweet-alerts.edit></x-sweet-alerts.edit>`, icon: 'question', showCancelButton: false, showConfirmButton: false, allowOutsideClick: false, allowEscapeKey: false, showCloseButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#cccccc', confirmButtonText: 'Button', cancelButtonText: 'Cancel' }); });
可选优化
如果.infinite-scroll是页面初始就存在的滚动容器,建议把事件委托到这个容器上,比委托到document更高效:
$('.infinite-scroll').on('click', '.__sweet_edit', function(e) { // 内部代码和上面一致即可 });
内容的提问来源于stack exchange,提问作者miftah
相关产品推荐
相关产品推荐

