26

按钮调用模式对话框:单击按钮时,触发事件,结果事件引用 e.relatedTarget 未定义。那么,如何从处理程序中获取调用按钮?e 似乎不包含对调用按钮的任何引用。

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

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

jQuery:

$('#myModal').on('show.bs.modal', function (e) {
  console.log(e.relatedTarget) // do something...
})

参考: http: //getbootstrap.com/javascript/#modals

4

5 回答 5

25

谢谢 Geo1004 .. 我已经在使用 JS 来触发模式上的“显示”事件,但我错过了第二个参数。所以 event.relatedTarget 是未定义的。

如果其他人正在使用 JS 路由(而不是使用数据属性),我会确保您将按钮作为 jQuery 对象发送 -

$( "#myModal" ).modal( "show", $( "#buttonBeingClicked" ) );
于 2015-08-17T20:14:00.277 回答
22

Take a look at the following Bootply example.

When run the show event seems to include a proper reference to e.relatedTarget.

$('#myModal').on('show.bs.modal', function (e) {
    var button = e.relatedTarget;
    if (button != null)
    {
        alert("Launch Button ID='" + button.id + "'");
    }
})

Take a look at the Bootply example to see if your own code deviates from it. (I copied the original Bootstrap sample code snippet directly from the link that you provided.)

I hope this helps. Good luck.

于 2014-05-27T17:56:52.053 回答
10

这是一种解决方法。您可以改为使用 JS 打开模式,并设置相关目标。您不应错过将按钮作为“模态”方法的第二个参数传递。

您将能够传递数据引用(此处为地址目标)

$('.listing_btn').on 'click', ->
  $('.modal').modal('show', $(@))

$('#modal').on 'show.bs.modal', (event)->
   button = $(event.relatedTarget)
   address_id = button.data('address-target')
   console.log address_id 

于 2015-08-17T16:31:23.297 回答
4

我遇到了同样的问题,浪费了整个晚上来解决它。我的 bootstrap.js 版本太旧了,并且 $(event.relatedTarget) 不适用于“show.bs.modal”事件。任何有同样问题的人都应该先检查他的引导程序版本。然后只需坚持官方网站示例: http: //getbootstrap.com/javascript/#modals-related-target 您将在 $(event.relatedTarget) 中找到您的参考。

于 2015-07-26T23:33:56.857 回答
2
$('#myModal').on('show.bs.modal', function (e) {
   console.log($(e.relatedTarget)); // You will get the element you want! Cheers
})
于 2017-05-01T11:19:58.697 回答