在
DOM 中注入的元素上不会触发甜蜜警报。
我在我的 rails 2 应用程序中使用了甜蜜的警报 5 gem (https://github.com/nicolasblanco/sweet-alert2-rails(,在我添加带有 js 响应的元素之前,它运行良好。我知道我必须在添加元素后通过调用它们来绑定甜蜜的警报事件侦听器,但我不知道如何。
gem 在某处初始化甜蜜警报并使用data-confirm
属性在我的 HTML 元素上绑定事件,将它们变成data-sweet-alert-confirm
。我想我必须在注入新元素后调用该 init 函数。
在查看文件中:
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>
<div id="append_div" style="margin:20px;"></div>
<button id="add_element">Add Element</button>
在 js 代码中:
<script>
$(document).ready(function(){
$(document).on('click', '#add_element', function(){
$(document).find('#append_div').append(
'<button class="_appended_btn" style="margin:10px;">Open sweet alert</button>'
);
});
$(document).on('click', '._appended_btn', function(){
Swal.fire({
type: 'success',
title: 'Your work has been done',
showConfirmButton: false,
timer: 1500
})
});
});
</script>