<a class="my_link" data-val="user1" href="#">modal link</a>
我有一个链接用于打开bootstrap模态框,但我需要传递数据属性"data-val"。我尝试使用JavaScript,但是没有成功。请问你能帮助我吗?
<a class="my_link" data-val="user1" href="#">modal link</a>
show.bs.modal
事件,获取作为事件relatedTarget
属性可用的单击元素。有关详细信息,请查看Bootstrap模态框文档。$('#my-modal').on('show.bs.modal', function (event) {
var myVal = $(event.relatedTarget).data('val');
$(this).find(".modal-body").text(myVal);
});
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<a href="#" class="my_link" data-val="user1" data-toggle="modal" data-target="#my-modal">Open Modal</a>
<div class="modal fade" id="my-modal" tabindex="-1" role="dialog" aria-labelledby="my-modal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">My Modal</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- jQuery, Popper and Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
relatedTarget
? - Abdullah Akçam你可以直接设置模态框
<div class="modal fade" id="setTypeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
然后使用以下方式调用
$('#setTypeModal').modal('show');
然后,您可以使用Jquery等工具访问模态中的元素。
最后,通过单击事件关闭模态并进行更多工作。
$('#setTypeModal').modal('hide');
href
或data-toggle
属性设置为带有#
符号的模态框的id
。无论如何,答案中有一个可工作的示例。 - rmalviya