我需要从多个按钮打开一个模态框
问题是它只在第一个按钮上工作。
例如:
<button id="myBtn" class="myBtn" style="cursor: pointer;">Click Me</button>
<button id="myBtn" class="myBtn" style="cursor: pointer;">Click Me</button>
这是模态框 -
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Modal Header</h2>
</div>
<div class="modal-body">
<p>Some text in the Modal Body</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3 style="margin: 5px ; ">Modal Footer</h3>
</div>
这是脚本:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
答案 0 :(得分:0)
您需要选择使用类名并使用索引号或循环获取数组项。
var btn = document.getElementsByClassName("myBtn");
btn[0].onclick = function() {
modal.style.display = "block";
};
btn[1].onclick = function() {
modal.style.display = "block";
};
请参阅此Pen。
答案 1 :(得分:0)
您可以使用Bootstrap,以便所有这些问题看起来如此简单:
您可以添加任意数量的按钮
请查看这些代码,但需要在代码中包含这些boottsrap cdn:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" id ="sample" data-toggle="modal" data-target="#myModal">Open Modal</button>
<button type="button" class="btn btn-info btn-lg" id ="sample" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>