You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript判断元素属性值是否在指定列表并为其子元素添加类

JavaScript 实现方案

核心功能代码

// 预设屏蔽用户列表,新增屏蔽用户只需添加到这里即可
const BLOCKED_USERS = new Set([
  'spam_imager',
  'another_spammer',
  'bad_user_001'
  // 按需添加更多用户名
])

// 处理单个帖子元素的函数
function processPostElement(postEl) {
  const posterName = postEl.getAttribute('poster-name')
  // 不在屏蔽列表直接跳过
  if (!posterName || !BLOCKED_USERS.has(posterName)) return

  // 查找需要屏蔽的子元素并添加类
  postEl.querySelectorAll('a.thumbnail, img.preview').forEach(el => {
    el.classList.add('spam_image_block')
  })
}

// 页面初始加载完成后处理已渲染的所有帖子
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('div[poster-name]').forEach(processPostElement)
})

// 可选:如果论坛有滚动加载/动态渲染新帖子的特性,保留这段监听动态新增的元素
const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    mutation.addedNodes.forEach(node => {
      if (node.nodeType === Node.ELEMENT_NODE) {
        // 新增节点本身是帖子div的情况
        if (node.hasAttribute('poster-name')) {
          processPostElement(node)
        }
        // 新增节点包含帖子div的情况
        node.querySelectorAll('div[poster-name]').forEach(processPostElement)
      }
    })
  })
})
// 监听整个文档的节点变动,也可以缩小监听范围到帖子列表容器提升性能
observer.observe(document.body, {
  childList: true,
  subtree: true
})

配套CSS规则

a.spam_image_block {
    visibility: hidden;
    /* display: none; (替代方案,直接不占用页面空间) */
}

img.spam_image_block {
    visibility: hidden;
    /* display: none; (替代方案,直接不占用页面空间) */
}

使用说明

  • 新增屏蔽用户时,只需往BLOCKED_USERS集合里添加对应用户名即可,无需修改其他代码或CSS
  • 如果论坛没有动态加载内容的特性,可以删除MutationObserver相关代码,减少性能占用
  • 如果能定位到帖子的外层容器,可以把observer.observe的第一个参数换成对应容器元素,进一步降低性能消耗

内容的提问来源于stack exchange,提问作者vfclists

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:39:01