Get the element whose click opened a Bootstrap Modal dialog

丶灬走出姿态 提交于 2021-02-08 12:59:15

问题


How do I know which button triggered the opening of a Bootstrap Modal Dialog?

<a href="#" data-toggle="modal" data-target="#myModal">
    Button 1
</a>  
<a href="#" data-toggle="modal" data-target="#myModal">
    Button 2
</a>

Javascript

$('#myModal').on('shown.bs.modal', function () {
  var triggerElement = ???
})

回答1:


Its documented here

$('#myModal').on('shown.bs.modal', function (event) {
     var triggerElement = $(event.relatedTarget); // Button that triggered the modal
});

Edit: As noted in comments, if buttons are dynamically generated we can attach an event listener to document:

$(document).on('shown.bs.modal', '#myModal', function (event) {
     var triggerElement = $(event.relatedTarget); // Button that triggered 
});


来源:https://stackoverflow.com/questions/39647983/get-the-element-whose-click-opened-a-bootstrap-modal-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!