我有两个超链接,每个都有一个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 3.2.0,这里有一个更干净的方法。
链接的HTML
<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>
JavaScript资本
//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {
//get data-id attribute of the clicked element
var bookId = $(e.relatedTarget).data('book-id');
//populate the textbox
$(e.currentTarget).find('input[name="bookId"]').val(bookId);
});
http://jsfiddle.net/k7FC2/
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
})
我发现这个方法很有用:
创建点击事件:
$( button ).on('click', function(e) {
let id = e.node.data.id;
$('#myModal').modal('show', {id: id});
});
创建show.bs.modal事件:
$('#myModal').on('show.bs.modal', function (e) {
// access parsed information through relatedTarget
console.log(e.relatedTarget.id);
});
额外的:
让你的逻辑在show.bs.modal中检查属性是否被解析,就像这样:
id:(e.r relatedtarget。hasOwnProperty('id') ?e.relatedTarget.id: null)