我一直在尝试实现这个问题的可接受答案,但未能获得要显示的模态。
应该触发模式的按钮编码如下:
<a class="btn btn-success btn-xs openModal" data-target="#myModal" data-id=1><span class="glyphicon glyphicon-edit"></span> Edit</a>
点击按钮时应该触发的脚本是:
<script>
alert("id=" + $(this).attr('data-id'));
$('.openModal').click(function () {
var id = $(this).attr('data-id');
$.ajax({url: "testModal.php?id=" + id, cache: false, success: function (result) {
$(".modal-content").html(result);
}});
});
</script>
我添加了一个alert()命令,这样我就可以判断脚本是否执行了。
当我点击任何应该触发它的按钮时,我都看不到警报对话框。当由于某种原因首次加载页面时,我确实看到了警报对话框。
我曾尝试将脚本放在html文件的头部分和正文部分的末尾,但在这两种情况下都没有执行。
模态的html是
<div style="margin-top:5%;" class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content"></div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Edit Venue</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
有人能解释一下为什么点击按钮时脚本没有被执行吗?
谢谢,Pete
将data-toggle
属性添加到锚点标签以显示模式
<a class="btn btn-success btn-xs openModal" data-toggle="modal" data-target="#myModal"
data-id=1><span class="glyphicon glyphicon-edit"></span> Edit</a>
实际上,脚本正在执行,但您将alert
放错了位置。尝试以下的代码
<script>
$('.openModal').click(function () {
alert("id=" + $(this).attr('data-id'));
var id = $(this).attr('data-id');
$.ajax({url: "testModal.php?id=" + id, cache: false, success: function (result) {
$(".modal-content").html(result);
$('#myModal').modal('show');// this is optional if adding data-toggle attribute does not work. try this. In your case, it's better to remove the data-toggle attribute and use this instead.
}});
});
</script>
PS:如果您在服务器端遇到错误,modal可能不会显示。
您可能需要考虑使用以下方法:
$('.openModal').on('shown.bs.modal', function () {
// Whatever you want to do here.
})
请务必查看引导程序文档。
旁注:我自己还没有试过这个代码。