设计思路
- 参数化筛选规则:使用对象来定义每组 DOM 节点的筛选规则,这样可以灵活配置不同的筛选条件。
- 操作函数的抽象:将对每组节点的不同操作也通过函数来抽象,使得每个操作可以独立定义和修改。
- 遍历执行:遍历每组筛选规则及其对应的操作函数,根据筛选规则找到相应的 DOM 节点,并执行对应的操作。
完整代码
function batchDOMOperations(operations) {
Object.keys(operations).forEach((group) => {
const { selector, action } = operations[group];
const nodes = document.querySelectorAll(selector);
nodes.forEach((node) => {
action(node);
});
});
}
// 使用示例
const operations = {
group1: {
selector: '.class1[data - type="type1"]',
action: (node) => {
node.style.color ='red';
}
},
group2: {
selector: '.class2[data - status="active"]',
action: (node) => {
node.textContent = 'New Text';
}
}
};
batchDOMOperations(operations);