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

无批量数据跨页传递方案:如何将列表选中行ID带至CUSTOM ACTION目标页?

Alright, let's walk through how to implement this feature—passing selected row IDs to the target page when clicking the "CUSTOM ACTION" button. I'll cover both vanilla JavaScript and React implementations since you didn't specify your tech stack.

Vanilla JavaScript Approach

Step 1: Basic HTML Structure

First, here's a sample markup for your list page:

<!-- Global checkbox -->
<input type="checkbox" id="select-all"> Select All

<!-- List rows -->
<ul id="item-list">
  <li>
    <input type="checkbox" class="row-checkbox" data-id="1"> Item 1
  </li>
  <li>
    <input type="checkbox" class="row-checkbox" data-id="2"> Item 2
  </li>
  <li>
    <input type="checkbox" class="row-checkbox" data-id="3"> Item 3
  </li>
</ul>

<!-- Custom Action Button -->
<button id="custom-action">CUSTOM ACTION</button>

Step 2: Add JavaScript Logic

We'll handle three key parts: syncing the "select all" checkbox, collecting selected IDs, and navigating with the IDs.

// Get elements
const selectAllCheckbox = document.getElementById('select-all');
const rowCheckboxes = document.querySelectorAll('.row-checkbox');
const customActionBtn = document.getElementById('custom-action');

// Sync select all with row checkboxes
selectAllCheckbox.addEventListener('change', (e) => {
  rowCheckboxes.forEach(checkbox => {
    checkbox.checked = e.target.checked;
  });
});

// Handle button click to pass IDs
customActionBtn.addEventListener('click', () => {
  // Collect all checked row IDs
  const selectedIds = Array.from(rowCheckboxes)
    .filter(checkbox => checkbox.checked)
    .map(checkbox => checkbox.dataset.id);

  // Handle case where no rows are selected
  if (selectedIds.length === 0) {
    alert('Please select at least one row!');
    return;
  }

  // Encode IDs to avoid URL issues (e.g., special characters)
  const encodedIds = encodeURIComponent(selectedIds.join(','));
  // Navigate to target page with IDs as URL parameter
  window.location.href = `/target-page?ids=${encodedIds}`;
});

On the target page, you can retrieve the IDs like this:

// Target page JS
const urlParams = new URLSearchParams(window.location.search);
const selectedIds = urlParams.get('ids')?.split(',') || [];
// Use selectedIds as needed
console.log('Selected IDs:', selectedIds);

React Approach

If you're using React, here's a clean implementation using state:

Step 1: Component Setup

import { useState } from 'react';
import { useNavigate } from 'react-router-dom'; // For React Router navigation

const ItemList = () => {
  const navigate = useNavigate();
  // Sample list data with IDs
  const items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' }];
  // State to track selected IDs
  const [selectedIds, setSelectedIds] = useState([]);

  // Handle single row checkbox toggle
  const handleRowCheckboxChange = (itemId) => {
    setSelectedIds(prev => 
      prev.includes(itemId) 
        ? prev.filter(id => id !== itemId) 
        : [...prev, itemId]
    );
  };

  // Handle select all checkbox toggle
  const handleSelectAllChange = (e) => {
    setSelectedIds(e.target.checked ? items.map(item => item.id) : []);
  };

  // Handle custom action button click
  const handleCustomAction = () => {
    if (selectedIds.length === 0) {
      alert('Please select at least one row!');
      return;
    }

    // Option 1: Pass via URL parameter
    const encodedIds = encodeURIComponent(selectedIds.join(','));
    navigate(`/target-page?ids=${encodedIds}`);

    // Option 2: Pass via React Router state (better for sensitive data)
    // navigate('/target-page', { state: { selectedIds } });
  };

  return (
    <div>
      {/* Select All Checkbox */}
      <input
        type="checkbox"
        onChange={handleSelectAllChange}
        checked={selectedIds.length === items.length}
      /> Select All

      {/* Item List */}
      <ul>
        {items.map(item => (
          <li key={item.id}>
            <input
              type="checkbox"
              checked={selectedIds.includes(item.id)}
              onChange={() => handleRowCheckboxChange(item.id)}
            />
            {item.name}
          </li>
        ))}
      </ul>

      {/* Custom Action Button */}
      <button onClick={handleCustomAction}>CUSTOM ACTION</button>
    </div>
  );
};

export default ItemList;

On the Target Page (React)

If you used URL parameters:

import { useSearchParams } from 'react-router-dom';

const TargetPage = () => {
  const [searchParams] = useSearchParams();
  const selectedIds = searchParams.get('ids')?.split(',') || [];

  return <div>Selected IDs: {selectedIds.join(', ')}</div>;
};

If you used React Router state:

import { useLocation } from 'react-router-dom';

const TargetPage = () => {
  const location = useLocation();
  const selectedIds = location.state?.selectedIds || [];

  return <div>Selected IDs: {selectedIds.join(', ')}</div>;
};

Key Notes

  • Always encode IDs when passing via URL to avoid issues with special characters.
  • Add validation for empty selections to prevent unnecessary navigation.
  • For sensitive data, prefer using state (in SPAs) instead of URL parameters since URLs are easily visible and shared.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:25:45