首页 > 解决方案 > 确认删除的引导模式

问题描述

当我遍历我的图像时,我有一个图标,您可以单击该图标来删除图像。相反,我希望弹出一个模式来确认删除。唯一的问题是我不想为每个图像重复模态代码。我需要一种将图像 ID 传递给模态的方法。

我在想我可以通过 id 传递,onClick但我不确定它是否适用于 Bootstrap 模态。

这是我目前删除的方式:

{% for image in images %}
  <img src="{{image.image.url}}">
  <form method="POST" action="{% url 'products:delete_image>
    {% csrf_token %}
    <button type="submit" rel="tooltip" title="Remove">
      <i class="material-icons">close</i>
    </button>
  </form>
{% endfor %}

这是我要集成的模态代码

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

标签: djangobootstrap-4

解决方案


为每个表单内的按钮分配一个点击处理程序,并为每个表单分配一个唯一的 id。例如,给所有表单按钮一个类,如confirm-delete. 分配一个点击处理程序(这是 jQuery,但你也可以使用 vanilla JS)...

$('.confirm-delete').on('click', function(e) {
    // prevent form submit
    e.preventDefault();
    
    // get the current image/form id
    var id = $(this).attr("id")
    
    // assign the current id to the modal and show the modal
    $('#myModal').data('id', id).modal('show');
})

然后在模态框内,有一个按钮,它使用传递的 id 实际执行删除data...

$('#btnDelete').click(function() {
    // handle deletion here
    var id = $('#myModal').data('id');
    
    // submit the form
    $('form'+id).submit();
    
    // if needed, remove deleted image 
    // and form from DOM
    $('#img'+id).remove();
    $('#form'+id).remove();
    
    // hide modal
    $('#myModal').modal('hide');
})

演示


推荐阅读