确定哪个按钮打开了 Bootstrap 3 模态

Determine which button opened a Bootstrap 3 modal

我有以下 Bootstrap 个按钮:

<button type="button" class="btn btn-primary btn-lg" data-button="create" data-toggle="modal" data-target="#modal">Create</button>
<button type="button" class="btn btn-primary btn-lg" data-button="delete" data-toggle="modal" data-target="#modal">Delete</button>

这是模态:

<div class="modal fade" id="modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

如何确定是哪个按钮触发了模式打开?

具体来说,我需要 data-button 属性。

您可以收听 show.bs.modal/shown.bs.modal 事件中的任何一个。

在函数中,事件附加了一个 relatedTarget 属性。您可以使用它来确定哪个按钮触发模式打开。

Bootstrap 3 - Modal events:

This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.

$('.modal').on('show.bs.modal', function (e) {
    var $trigger = $(e.relatedTarget);
});

Example Here

.. 如果您想访问 data-button 属性,请使用:

$(e.relatedTarget).data('button');

相反,如果您想确定哪个按钮导致模式关闭,请参阅