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

如何基于值和父ID为不同Item筛选勾选复选框?

Fixing Tampermonkey Checkbox Selection Scope Issue

Got it, let's tackle this problem head-on. The core issue here is that your current script is targeting checkboxes globally across the page—we need to narrow that scope to each individual Item first, then select the right checkboxes inside it. Here's a step-by-step solution tailored to your needs:

1. First, Define Your Target Mapping

Start by creating a clear configuration object that maps each Item (by ID or title) to the checkbox values you want pre-selected. This makes your script easy to maintain:

// Configure which checkboxes to select for each Item
const itemToCheckboxes = {
  "item-123": ["value1", "value3"], // Key is Item's ID
  "Monthly Report": ["value2"],      // Key is Item's title text
  // Add more Item mappings here
};

2. Option 1: Target Items by Their ID

If each Item has a unique id attribute (e.g., <div id="item-123" class="item">), use this approach to scope your checkbox selection:

// Iterate over each Item in our config
for (const [itemId, targetValues] of Object.entries(itemToCheckboxes)) {
  // Find the specific Item element
  const targetItem = document.getElementById(itemId);
  if (!targetItem) continue; // Skip if Item doesn't exist

  // ONLY look for checkboxes INSIDE this Item
  const checkboxes = targetItem.querySelectorAll('input[type="checkbox"]');
  
  // Check matching values
  checkboxes.forEach(checkbox => {
    if (targetValues.includes(checkbox.value)) {
      checkbox.checked = true;
      // Optional: Trigger a change event to trigger any page logic tied to the checkbox
      checkbox.dispatchEvent(new Event('change', { bubbles: true }));
    }
  });
}

3. Option 2: Target Items by Their Title Text

If Items don't have unique IDs but do have a distinct title (e.g., <h3 class="item-title">Monthly Report</h3> inside the Item), adjust the script to locate Items via their title:

for (const [itemTitle, targetValues] of Object.entries(itemToCheckboxes)) {
  // Find the title element matching our config
  const titleElement = document.querySelector(`.item-title:contains("${itemTitle}")`);
  if (!titleElement) continue;

  // Get the parent Item element (adjust the selector to match your DOM structure)
  const targetItem = titleElement.closest('.item');
  if (!targetItem) continue;

  // Same checkbox selection logic as above, scoped to this Item
  const checkboxes = targetItem.querySelectorAll('input[type="checkbox"]');
  checkboxes.forEach(checkbox => {
    if (targetValues.includes(checkbox.value)) {
      checkbox.checked = true;
      checkbox.dispatchEvent(new Event('change', { bubbles: true }));
    }
  });
}

4. Handle Dynamic Content (If Needed)

If your page loads Items dynamically (e.g., infinite scroll), use a MutationObserver to trigger the selection logic whenever new Items are added:

// Wrap selection logic in a reusable function
function applyCheckboxSelections() {
  const itemToCheckboxes = {
    "item-123": ["value1", "value3"],
    "Monthly Report": ["value2"],
  };

  // Insert your chosen selection logic (Option 1 or 2) here
}

// Run once on initial page load
applyCheckboxSelections();

// Listen for dynamic DOM changes
const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    if (mutation.addedNodes.length > 0) {
      applyCheckboxSelections();
    }
  });
});

// Observe the parent container of all Items (adjust selector to your page)
observer.observe(document.querySelector('.items-container'), {
  childList: true,
  subtree: true
});

Key Notes

  • Always adjust selectors (like .item, .item-title) to match your actual page's DOM structure.
  • Use @run-at document-end in your Tampermonkey script header to ensure the DOM is loaded before your script runs:
    // ==UserScript==
    // @name         Item Checkbox Preselector
    // @namespace    http://tampermonkey.net/
    // @version      0.1
    // @description  Preselect checkboxes per Item
    // @author       You
    // @match        https://your-target-page.com/*
    // @run-at       document-end
    // ==/UserScript==
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:59:41