我在我的网站上创建了一个弹出窗口,它分配给三个按钮,但我在所有按钮上都有相同的ID,所以当我点击第三个按钮打开弹出窗口时,它会给我第一个弹出窗口,与第二个按钮相同。
我已经提出了类似的问题,但是我得到的反馈和答案,我无法实现它们,因为我是javascript的新手并且没有太多经验所以我试图修复它几个小时我我还没有运气。
这是javascript:
var modal = document.getElementById('myModal');
var btns = document.getElementsByClassName("myBtn");
var showModal = function() {
modal.style.display = "block";
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', showModal, false);
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
这是html:
<footer class="panel-footer">
<div class="btn btn-block btn-lg btn-default">
<button id="myBtn">Sign up now</button>
<div id="myModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2><img src="http://localhost:8383/homepage/img/logo.png" style="width:250px"></h2>
</div>
<div class="modal-body">
<h4><b><u>Sign up for a basic subscription</u></b></h4><br>
<form method="post" action="contact_basic.php" name="contactform" id="contactform">
<div class="results"></div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="sr-only">Name</label>
<input name="name" type="text" class="form-control input-lg" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input name="email" type="email" class="form-control input-lg" placeholder="Email" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="sr-only">Phone Number</label>
<input name="phone" type="number" class="form-control input-lg" placeholder="Phone Number" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="sr-only">Organization Name</label>
<input name="orgName" type="text" class="form-control input-lg" placeholder="Organization Name">
</div>
</div>
<div class="col-sm-3 col-xs-12">
<button id="submit" type="submit" align="center" class="btn btn-danger btn-lg btn-block">Send</button>
</div>
</div>
</div>
</div>
</div>
</div>
</footer>
答案 0 :(得分:1)
<强> Working fiddle 强>
id
属性在同一文档中应该是唯一的,因此您只需用class
属性替换这些ID,例如:
<button id="myBtn">Sign up now</button>
将是:
<button class="myBtn">Sign up now</button>
然后在你的js中将click事件附加到这个类的所有元素:
var btns = document.getElementsByClassName("myBtn");
var showModal = function() {
modal.style.display = "block";
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', showModal, false);
}
希望这有帮助。