如何在没有 Id 的情况下获取 Bootstrap 模态?
How to get the Bootstrap modal without Id?
我的应用程序中有多个 bootstrap 模态,我想在每个模态 shown.bs.modal
事件上调用相同的函数。我想在一个地方全局执行此操作,但困扰我的是此事件需要特定模式的 id
属性,如下所示:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
我想知道有没有什么办法可以在全局范围内做到这一点,只要有一些模态显示,然后一个函数调用?
您可以使用Class模型名称
$('.modelClassName').on('shown.bs.modal', function () {
$('#myInput').focus()
})
尝试 class
$('.classNameOfModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
考虑通过 class 名称访问。点'.'用于 class.
$('.myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
$('#myModal')
只是一个 jQuery 选择器。阅读 more 关于 jQuery 选择器的内容。我们可以用 $()
写任何东西,比如:
$("#myModal") // Select an element with id "myModal"
$("body > #myModal") // Select an element with id "myModal" which is a immediate child of the "body" tag
$("#foo .modal") // Select all elements with a class "modal" which is inside an element with id "foo"
因此,在 Bootstrap 中,每个模态框都有一个 class .modal
,您可以简单地使用那个 class 来附加一个全局侦听器:
$('.modal').on('shown.bs.modal', function () {
$('#myInput').focus()
});
或者,就像其他人提到的那样,您可以为所有要执行一些常见操作的模态框添加 class,例如 do-common-stuff
:
<div class="modal do-common-stuff" id="foo">...</div>
<div class="modal" id="bar">...</div>
<div class="modal do-common-stuff" id="tango">...</div>
以后,
$('.do-common-stuff').on('shown.bs.modal', function () {
$('#myInput').focus()
});
这对我来说效果很好。
$(window).on("shown.bs.modal", function () {
//Do what ever you want here...
});
我的应用程序中有多个 bootstrap 模态,我想在每个模态 shown.bs.modal
事件上调用相同的函数。我想在一个地方全局执行此操作,但困扰我的是此事件需要特定模式的 id
属性,如下所示:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
我想知道有没有什么办法可以在全局范围内做到这一点,只要有一些模态显示,然后一个函数调用?
您可以使用Class模型名称
$('.modelClassName').on('shown.bs.modal', function () {
$('#myInput').focus()
})
尝试 class
$('.classNameOfModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
考虑通过 class 名称访问。点'.'用于 class.
$('.myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
$('#myModal')
只是一个 jQuery 选择器。阅读 more 关于 jQuery 选择器的内容。我们可以用 $()
写任何东西,比如:
$("#myModal") // Select an element with id "myModal"
$("body > #myModal") // Select an element with id "myModal" which is a immediate child of the "body" tag
$("#foo .modal") // Select all elements with a class "modal" which is inside an element with id "foo"
因此,在 Bootstrap 中,每个模态框都有一个 class .modal
,您可以简单地使用那个 class 来附加一个全局侦听器:
$('.modal').on('shown.bs.modal', function () {
$('#myInput').focus()
});
或者,就像其他人提到的那样,您可以为所有要执行一些常见操作的模态框添加 class,例如 do-common-stuff
:
<div class="modal do-common-stuff" id="foo">...</div>
<div class="modal" id="bar">...</div>
<div class="modal do-common-stuff" id="tango">...</div>
以后,
$('.do-common-stuff').on('shown.bs.modal', function () {
$('#myInput').focus()
});
这对我来说效果很好。
$(window).on("shown.bs.modal", function () {
//Do what ever you want here...
});