获取其单击打开Bootstrap Modal对话框的元素

时间:2016-09-22 20:05:00

标签: javascript jquery twitter-bootstrap-3

如何知道哪个按钮触发了Bootstrap模态对话框的打开?

<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 个答案:

答案 0 :(得分:8)

记录在案here

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

修改 如评论中所述,如果按钮是动态生成的,我们可以将事件监听器附加到文档:

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