gpt4 book ai didi

javascript - 如何自动检测 DOM 中的元素以填充 const 数组?

转载 作者:行者123 更新时间:2023-12-02 23:45:38 27 4
gpt4 key购买 nike

我编写了一个几乎可以独立运行的脚本,但问题是,如果我向页面添加另一个模式,我需要进入我的脚本添加一个条目才能被它识别。我想知道是否有一种方法可以让脚本自动检测页面上的模态数量,并在我的 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]);
}

最佳答案

您已经使用 document.querySelectorAll('.staff-modal') 选择了所有模式。无需手动编写 staffModal 对象,只需迭代您选择的所有内容即可:

for (let i = 0; i < modalMain.length; i++) {
modalFunction({button: modalButton[i], modal: modalMain[i] , close: modalClose[i]});
}

此外,我不会从所有模态中选择所有元素并假设它们的顺序相同。我不确定是否确实存在一些奇怪的情况,但最好只选择父模态和随后的子模态。像这样:

const modalMain = document.querySelectorAll('.staff-modal');

function modalFunction(modal) {
const modalOpen = modal.querySelector('.staff-modal-button p');
const modalExit = modal.querySelector('.modal-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'
}
})
}

for (let i = 0; i < modalMain.length; i++) {
modalFunction(modalMain[i]);
}

关于javascript - 如何自动检测 DOM 中的元素以填充 const 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867796/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com