我已經(jīng)編寫了一個(gè)腳本,該腳本幾乎可以單獨(dú)工作,但是問題是,如果我向頁面添加另一個(gè)模式,則需要進(jìn)入腳本以添加一個(gè)條目,使其能夠被它識(shí)別。我想知道是否有一種方法可以讓腳本自動(dòng)檢測頁面上的模態(tài)數(shù)量,并在const中自動(dòng)為其指定適當(dāng)?shù)闹担缓蟀凑漳_本的指示在其上運(yùn)行函數(shù)。這是我的代碼。// Staff Modal Element Arraysconst modalClose = document.querySelectorAll('.modal-close');const modalButton = document.querySelectorAll('.staff-modal-button p')const modalMain = document.querySelectorAll('.staff-modal')// Staff Modal Combined Definition Arrayconst 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 Actionsfunction 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 Arrayfor (i in staffModal) { modalFunction(staffModal[i]);}
如何自動(dòng)檢測DOM中的元素以填充const數(shù)組?
BIG陽
2021-04-30 13:27:32