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

在JavaScript中插入含PHP代码的HTML片段失败问题排查及解决方案咨询

Troubleshooting and Fixing Your Dynamic Banner Insertion Code

Let's break down the issues in your current JavaScript code and walk through actionable fixes step by step:

1. HTMLCollection vs. Single Element Mismatch

document.getElementsByClassName("wapf-product-totals") returns an HTMLCollection (a set of elements) rather than a single DOM node. Passing this directly to insertAfter will fail because the function expects a single reference element. You need to target the first matching element (assuming only one exists on the page) and add a safety check to avoid errors if the element isn't found:

var totalsContainer = document.getElementsByClassName("wapf-product-totals")[0];
if (!totalsContainer) {
  console.warn("Target totals container not found on the page");
  return;
}

2. PHP Code in Client-Side JavaScript

Your JS includes raw PHP <?php _e(...) ?>, which won't work as intended. PHP runs on the server before the page is sent to the browser, so this snippet will be treated as plain text instead of parsed into a translated string.

In WordPress, the standard way to pass server-side values (like translations) to JS is using wp_localize_script. Add this to your theme's functions.php or a custom plugin:

function enqueue_custom_wapf_banner_script() {
  // Enqueue your custom JS file (adjust the path to match your setup)
  wp_enqueue_script('custom-wapf-banner', get_stylesheet_directory_uri() . '/js/custom-wapf-banner.js', array('jquery'), '1.0', true);
  
  // Pass translated text to your JavaScript
  wp_localize_script('custom-wapf-banner', 'WAPFBanner', array(
    'grandTotalText' => __('Grand total: ', 'advanced-product-fields-for-woocommerce')
  ));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_wapf_banner_script');

Then in your JS, reference the translated text using WAPFBanner.grandTotalText instead of the PHP snippet.

3. DOM Readiness Timing

If your JS runs before the wapf-product-totals element loads into the DOM, it won't find the element and the insertion will fail. Wrap your code in a DOMContentLoaded listener to ensure it runs only after the page is fully rendered:

document.addEventListener('DOMContentLoaded', function() {
  // Your insertion logic goes here
});

4. Syncing Dynamic Total Updates

Since the original plugin updates the total dynamically when product features change, you need to make sure your new banner's total stays in sync. Use a MutationObserver to watch for changes to the original total element and mirror them to your banner.

Full Corrected Code

JavaScript (custom-wapf-banner.js)

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

document.addEventListener('DOMContentLoaded', function() {
  // Target the totals container
  const totalsContainer = document.querySelector('.wapf-product-totals');
  if (!totalsContainer) {
    console.warn('WAPF product totals container not found');
    return;
  }

  // Build the banner element with translated text
  const bannerEl = document.createElement('div');
  bannerEl.innerHTML = `
    <div class="gt-banner-message">
      <div class="total-wrap">
        <span>${WAPFBanner.grandTotalText}</span>
        <span class="wapf-grand-total price amount"></span>
      </div>
    </div>
  `;

  // Insert the banner after the totals container
  insertAfter(totalsContainer, bannerEl);

  // Sync total updates from the original element
  const originalTotal = document.querySelector('.wapf-product-totals .wapf-grand-total');
  const bannerTotal = bannerEl.querySelector('.wapf-grand-total');

  if (originalTotal && bannerTotal) {
    // Initial sync to set the starting total
    bannerTotal.innerHTML = originalTotal.innerHTML;

    // Watch for changes to the original total
    const observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if (mutation.type === 'childList' || mutation.type === 'characterData') {
          bannerTotal.innerHTML = originalTotal.innerHTML;
        }
      });
    });

    observer.observe(originalTotal, {
      childList: true,
      subtree: true,
      characterData: true
    });
  }
});

PHP Alternative (Inline Script for Simple Setups)

If you don't want to enqueue a separate JS file, add this directly to your theme's template (e.g., single-product.php) before your custom JS:

<script>
var WAPFBanner = {
  grandTotalText: "<?php echo esc_js(__('Grand total: ', 'advanced-product-fields-for-woocommerce')); ?>"
};
</script>

Quick Tips

  • Clear your WordPress and browser cache after making changes to ensure you see the updated code.
  • If the wapf-product-totals element loads dynamically (via AJAX), replace the DOMContentLoaded listener with a MutationObserver that watches for the element to be added to the DOM.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 23:43:15