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

如何高效遍历表格渲染PayPal按钮?替代硬编码ID方案

Hey there! I’ve run into similar dynamic rendering issues before, so let’s walk through a couple of clean, scalable solutions for your PayPal button problem—no more hardcoding selectors!

Solution 1: Target All Matching IDs with a Dynamic Selector

Since your IDs follow a consistent pattern (elX_qryMyReservedSlots_Payment), we can use CSS attribute selectors to grab all matching elements in one go. This works regardless of how many rows your table has.

Here’s the code:

// Grab every element whose ID starts with "el" and ends with your payment suffix
document.querySelectorAll('[id^="el"][id$="_qryMyReservedSlots_Payment"]').forEach(container => {
  paypal.Button.render({
    // ...your existing PayPal configuration (client IDs, styles, etc.)
  }, container);
});

How this works:

  • [id^="el"] matches any element whose ID starts with "el"
  • [id$="_qryMyReservedSlots_Payment"] narrows it down to elements that end with your specific payment suffix
  • Combining both selectors ensures we only target exactly the containers you need, then we loop through each to render the button.

Solution 2: Traverse the Table Directly (More Robust)

If you want to avoid relying on ID naming rules (in case they change later), you can target the table structure directly—since you know the button goes in the last cell of each row.

Assuming your table has an ID like reserved-slots-table, use this:

// Wait for the DOM to be fully loaded before running
document.addEventListener('DOMContentLoaded', () => {
  // Get all rows in the table's body (skip the header if you have one)
  const tableRows = document.querySelectorAll('#reserved-slots-table tbody tr');

  tableRows.forEach(row => {
    // Grab the last <td> in the row
    const lastCell = row.querySelector('td:last-child');
    
    if (lastCell) {
      // Optional: If the cell has the specific ID, target that instead of the cell itself
      const buttonContainer = lastCell.querySelector('[id$="_qryMyReservedSlots_Payment"]') || lastCell;
      
      paypal.Button.render({
        // ...your PayPal configuration
      }, buttonContainer);
    }
  });
});

Bonus Tips:

  • Make sure the PayPal script is loaded before running this code—wrap it in DOMContentLoaded or use PayPal's own callback if you're loading their script asynchronously.
  • If your table loads dynamically (e.g., via AJAX), run this code right after the table is inserted into the DOM, not on initial page load.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:34:53