Tampermonkey脚本求助:为HTML列表项添加递增序号
Tampermonkey脚本:为通知列表添加序号(优先提取内置序号)
解决方案思路
- 优先从列表项内
aria-label属性中提取形如(1 of 22)的序号直接显示 - 对无内置序号的项,使用递增索引作为序号
- 为序号添加样式,确保长列表中清晰可见
完整脚本
// ==UserScript== // @name 通知列表序号增强 // @namespace http://tampermonkey.net/ // @version 0.2 // @description 为通知列表添加序号,优先显示aria-label中的内置序号 // @author You // @include /^https?://warnerhotels\.eu\.qualtrics\.com/* // @grant GM_addStyle // ==/UserScript== (function() { 'use strict'; // 为序号添加自定义样式 GM_addStyle(` .notification-sequence-number { display: inline-block; margin-right: 8px; padding: 2px 6px; background-color: #f0f0f0; border-radius: 4px; font-weight: bold; color: #333; } `); // 定位目标通知列表 const notificationList = document.querySelector('ul[data-testid="notifications-list"]'); if (!notificationList) return; // 获取所有通知项 const notificationItems = notificationList.querySelectorAll('li[data-testid="notification-container"]'); if (!notificationItems.length) return; // 遍历处理每个通知项 notificationItems.forEach((item, index) => { // 查找包含aria-label的通知容器 const notificationDiv = item.querySelector('div[data-testid="notification"]'); let sequenceNumber = index + 1; // 默认使用递增序号 // 尝试从aria-label提取内置序号 if (notificationDiv?.ariaLabel) { const match = notificationDiv.ariaLabel.match(/\((\d+) of \d+\)/); if (match && match[1]) { sequenceNumber = match[1]; } } // 创建序号元素 const numberSpan = document.createElement('span'); numberSpan.className = 'notification-sequence-number'; numberSpan.textContent = sequenceNumber; // 将序号插入到通知标题前(优先)或项开头 const headerText = item.querySelector('h3.header-text--TaaKMDumePzcO7v'); if (headerText) { headerText.prepend(numberSpan); } else { item.prepend(numberSpan); } }); })();
关键代码说明
- 精准定位:使用
data-testid而非class选择元素,避免页面样式更新导致脚本失效 - 序号提取:通过正则表达式
/\((\d+) of \d+\)/精准匹配aria-label中的序号部分 - 样式隔离:用自定义类名添加样式,不污染页面原有样式
- 容错处理:对不存在的元素做可选链判断,避免脚本运行报错
内容的提问来源于stack exchange,提问作者Rodp
相关产品推荐
相关产品推荐

