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

Greasemonkey技术问题:优化含数字与文本的jQuery选择器

优化你的Greasemonkey脚本选择器:简洁高效方案

嘿,作为新手能写出实现功能的脚本已经超棒了!咱们来把你的脚本优化得更简洁、易维护,还能提升一点性能~

核心优化方向:合并重复操作,减少DOM查询

你的原脚本多次调用remove(),每次都要单独查询DOM,既冗余又影响性能。咱们可以把所有要移除的元素选择器合并,一次性完成操作。

基础优化版:合并选择器

直接把所有目标选择器用逗号分隔,一次调用remove():

// ==UserScript==
// @name         hide-unwanted-element
// @include      https:///*
// @description  Hides elements I don't want to see in the search result
// @require      http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant        GM_addStyle
// ==/UserScript==

// 合并所有要移除的元素选择器,一次性删除
$("h5:contains('Animation Série'), h5:contains('Animation'), h5:contains('Concert'), h5:contains('Documentaire'), div[category-id='2178'], div[category-id='你的其他ID']").remove();

进阶优化版:用数组管理规则(更易维护)

如果之后要新增/修改要隐藏的关键词或分类ID,直接修改数组就行,不用动选择器字符串,非常适合长期维护:

// ==UserScript==
// @name         hide-unwanted-element
// @include      https:///*
// @description  Hides elements I don't want to see in the search result
// @require      http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant        GM_addStyle
// ==/UserScript==

// 把要隐藏的文本关键词和分类ID都存到数组里
const hiddenTexts = ['Animation Série', 'Animation', 'Concert', 'Documentaire'];
const hiddenCategoryIds = ['2178', '1234', '5678']; // 替换成你的其他ID

// 生成文本匹配的选择器
const textSelectors = hiddenTexts.map(text => `h5:contains('${text}')`).join(', ');
// 生成分类ID匹配的选择器
const categorySelectors = hiddenCategoryIds.map(id => `div[category-id='${id}']`).join(', ');

// 合并所有选择器并删除元素
$(textSelectors + ', ' + categorySelectors).remove();

额外小技巧:解决大小写敏感问题

默认的:contains()是区分大小写的,如果想忽略大小写(比如页面里出现animation也想隐藏),可以用filter()自定义匹配逻辑:

// 替换上面的删除逻辑为:
$('h5').filter(function() {
  // 检查当前h5的文本是否包含任意一个关键词(忽略大小写)
  return hiddenTexts.some(text => 
    $(this).text().toLowerCase().includes(text.toLowerCase())
  );
})
// 加上分类ID的元素
.add(categorySelectors)
// 一次性删除
.remove();

这样你的脚本不仅更简洁,后续维护也会轻松很多~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:25:48