两个或两个以上具有相同功能的按钮.如何



我有两个按钮(但实际上我想要更多的按钮(。我希望他们两个打开相同的模态弹出窗口。这有可能吗?也许我必须使用某种身份证?

因此:步骤1:按下按钮1->打开模态&你可以再次关闭

步骤2:按下按钮2->打开相同的模态&你可以再次关闭

模式按钮将有一个输入字段、一个选择字段和一个将插入的信息添加到表中的按钮。我已经有了这个函数,但我没有把它们包含在代码中。我只想给你看必要的代码:(

欢迎您测试代码,了解我想要什么:(

const modal = document.querySelector(".modal");
const trigger = document.querySelector(".trigger");
const closeButton = document.querySelector(".close");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 1rem 1.5rem;
width: 24rem;
border-radius: 0.5rem;
}
.close-button {
float: right;
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
cursor: pointer;
border-radius: 0.25rem;
background-color: lightgray;
}
.close-button:hover {
background-color: darkgray;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1.0);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<table id="table" border="2" class="fruitTable">
<tr>
<th colspan="2">Apple
<button class="trigger">Click here to trigger the modal!</button></th>
</tr>
</table>
<table id="table" border="2" class="mitarbeiterTabelle">
<tr>
<th colspan="2">Banana
<button class="trigger">Click here to trigger the modal!</button></th>
</tr>
</table>

<div id="myModal" class="modal">  
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
I want to eat a lot. This modal will have more functions later (like an Input field and a button...)
</div>
</div>
</div>

您可以使用.querySelectorAll((来获取匹配元素的集合(.trigger(,并向所有元素添加相同的事件侦听器:

const modal = document.querySelector(".modal");
const triggers = document.querySelectorAll(".trigger");
const closeButton = document.querySelector(".close");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
triggers.forEach(function (x){  
x.addEventListener("click", toggleModal);
});
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

最新更新