当我以编程方式调用它时如何将参数传递给模态?

How to pass parameters to modal when i call it programmatically?

我像这样以编程方式调用 bootstrap 模态

$('#confirmModal').modal()

但是当我这样做时,"event" 在:

$('#confirmModal').on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget); 
})

没有 "relatedTarget" 但我需要它。如何使用 $('#confirmModal').modal()

传递它

您不能设置relatedTarget,它是事件的只读属性。 show.bs.modal 是由 bootstrap 模态本身触发的 BTW,所以无论哪种方式你都迷路了。

但是为什么不通过编程方式触发模态触发按钮的click事件,它会确切与调用modal()相同,然后relatedTarget 存在:

$("#button").click();

假设你已经像这样 "modal trigger button" 格式正确:

<button id="button" data-toggle="modal" data-target="#confirmModal">show modal</button>

看这里 -> http://jsfiddle.net/y3s1t7ea/

虽然不是 officially documented,但可以将第二个参数传递给作为相关目标的 modal()

$('#confirmModal').modal('show', $('#someButton'));

然后您可以使用事件处理程序,因为它会被按钮或其他任何东西触发:

$('#confirmModal').on('show.bs.modal', function (event) {
   var button = event.relatedTarget; // should be set now
})

这应该至少适用于 Bootstrap 3.3.x 我想也适用于 4.0.x.