我有两个超链接,每个都有一个ID附加。当我点击这个链接时,我想打开一个模态(http://twitter.github.com/bootstrap/javascript.html#modals),并将这个ID传递给模态。我在谷歌上搜索,但我找不到任何可以帮助我的东西。
这是代码:
<a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>
应该打开:
<div class="modal hide" id="addBookDialog">
<div class="modal-body">
<input type="hidden" name="bookId" id="bookId" value=""/>
</div>
</div>
下面这段代码:
$(document).ready(function () {
$(".open-AddBookDialog").click(function () {
$('#bookId').val($(this).data('id'));
$('#addBookDialog').modal('show');
});
});
然而,当我点击超链接时,什么都没有发生。当我给超链接<a href="#addBookDialog"…>,模态打开得很好,但它不包含任何数据。
我遵循了这个例子:如何在Bootstrap中将值参数传递给modal.show()函数
(我也试过这个:如何在模态对话中设置输入值?)
我是bootstrap 5,由于我控制之外的约束,我不能显示()脚本的模态,所以我依赖于弹出模态的按钮的属性data-b -toggle和data-b -target。
Bootstrap暴露了一些事件(https://getbootstrap.com/docs/5.0/components/modal/),我们可以像这样钩住代码:
document.getElementById('idModal').addEventListener('show.bs.modal', (e) => {
console.log(e.relatedTarget);
});
在relatedTarget中,我们将在dataset中找到指定的数据属性,例如,如果我们有一个看起来像这样的元素:
<button
class="btn btn-secondary"
data-id="fk_articles"
data-bs-toggle="modal"
data-bs-target="#documentationModal">
Documentation
</button>
然后我们可以通过以下方式到达fk_articles:
console.log( e.relatedTarget.dataset.id )
Bootstrap 4.0提供了一个修改选项
模态数据使用jquery: https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content
下面是文档中的script标签:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
它在大多数情况下是有效的。只有对modal的调用不工作。
以下是对脚本的修改,为我工作:
$(document).on('show.bs.modal', '#exampleModal',function(event){
... // same as in above script
})