我已经编写了一个脚本,该脚本几乎可以单独工作,但是问题是,如果我向页面添加另一个模式,则需要进入脚本以添加一个条目,使其能够被它识别。我想知道是否有一种方法可以让脚本自动检测页面上的模态数量,并在const中自动为其指定适当的值,然后按照脚本的指示在其上运行函数。这是我的代码。
// Staff Modal Element Arrays
const modalClose = document.querySelectorAll('.modal-close');
const modalButton = document.querySelectorAll('.staff-modal-button p')
const modalMain = document.querySelectorAll('.staff-modal')
// Staff Modal Combined Definition Array
const staffModal = {one: {button: modalButton[0], modal: modalMain[0] , close: modalClose[0]},
two: {button: modalButton[1], modal: modalMain[1], close: modalClose[1]},
three: {button: modalButton[2], modal: modalMain[2], close: modalClose[2]},
four: {button: modalButton[3], modal: modalMain[3], close: modalClose[3]},
five: {button: modalButton[4], modal: modalMain[4], close: modalClose[4]},
six: {button: modalButton[5], modal: modalMain[5], close: modalClose[5]},
seven: {button: modalButton[6], modal: modalMain[6], close: modalClose[6]}}
// Function to Define Modal Actions
function modalFunction(staffNumber) {
const modalOpen = staffNumber.button;
const modal = staffNumber.modal;
const modalExit = staffNumber.close;
modalOpen.addEventListener('click', function() {
modal.style.display='flex';
})
modalExit.addEventListener('click', function() {
modal.style.display='none';
})
modal.addEventListener('click', function(e) {
if (e.target == modal) {
modal.style.display='none'
}
})
}
// Calling Functions for Each Staff Modal in Array
for (i in staffModal) {
modalFunction(staffModal[i]);
}
相关分类