我有两个超链接,每个都有一个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/
如果你是在引导3+,这可以缩短一点,如果使用Jquery。
HTML
<a href="#" data-target="#my_modal" data-toggle="modal" class="identifyingClass" data-id="my_id_value">Open Modal</a>
<div class="modal fade" id="my_modal" tabindex="-1" role="dialog" aria-labelledby="my_modalLabel">
<div class="modal-dialog" role="dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal Title</h4>
</div>
<div class="modal-body">
Modal Body
<input type="hidden" name="hiddenValue" id="hiddenValue" value="" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary">Yes</button>
</div>
</div>
</div>
JQUERY
<script type="text/javascript">
$(function () {
$(".identifyingClass").click(function () {
var my_id_value = $(this).data('id');
$(".modal-body #hiddenValue").val(my_id_value);
})
});
</script>
如果你使用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/
我发现这个方法很有用:
创建点击事件:
$( 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)