首页 > 解决方案 > 在 AJAX 调用后将“表”类应用于 WooCommerce 表

问题描述

WooCommerce-tables 带有这些类,开箱即用:shop_table shop_table_responsive cart woocommerce-cart-form__contents. 所以没有table-class,这意味着没有漂亮的引导表。

哼!

并且由于仅在绝对必要时才应覆盖 WooCommerce 模板,所以让我们用 JavaScript 解决它!

我的整个站点由 Vue-div 封装,如下所示:

<div id="app">
  ...
  <table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents">
    ...
    ...
  </table>
  ... 
</div>

所以最初我编写了这段代码,将table-class 添加到所有表中:

let tableSelectors = [
  '.some-class table',
  '.woocommerce-product-attributes',
  '.woocommerce-cart-form > table'
];
for( let t = 0; t < tableSelectors.length; t++ ){
  let tables = document.querySelectorAll( tableSelectors[t] );
  if( tables ){
    for( let i = 0; i < tables.length; i++ ){
      tables[i].classList.add( 'table' );
    }
  }
}

...把它放在 - 部分mounted(){ ... }

那行得通!到目前为止,一切都很好。

但是 WooCommerce 大量使用 jQuery。在购物车页面上,如果我更改数量(并按“更新”),则使用 AJAX 更新表格内容。如果你好奇它是如何工作的,那么你可以在这里查看

当它运行时,我假设 WooCommerce 会抓取初始购物车模板并重新加载整个表格;没有新添加的table-class。呸骗子!

那么我该如何解决呢?

  1. 我可以覆盖 WooCommerce ./cart/cart.php-模板并将类添加到模板中。添加课程似乎有点矫枉过正。

  2. 我可以每秒(左右)扫描 DOM 中的表并应用表类,如果它不存在的话。不酷......不管它是使用 jQuery 还是 Vue 完成的。

由于整个表在 DOM 中被替换,因此监视当前表(在 Vue 中使用 watch(){...} )并在它发生变化时应用类,因为它永远不会改变(它是替换)。

我找不到可以使用的 Hook。

我也尝试过使用ajaxComplete,但我可以在网络选项卡中看到 XHR 请求正在触发,但这里的代码从不做任何事情(在控制台中):

jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
    console.log( 'Test' );
});

还有其他建议吗?

标签: javascriptjquerywoocommerce

解决方案


您可以使用Mutation Observer API来侦听包装元素内容的更改并重新应用表类。

此示例几乎是从MDN 上的示例代码中逐字提取的。单击按钮会替换 div 的内容,您可以从控制台输出中看到它会触发观察者回调。

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = {
  childList: true,
  subtree: true
};

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
  for (let mutation of mutationsList) {
    if (mutation.type === 'childList') {
      console.log('A child node has been added or removed.');
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

function doUpdate() {
  targetNode.innerText = Math.random();
}

document.querySelector('button').addEventListener('click', doUpdate);
<div id="some-id">(container)</div>
<button>change</button>


推荐阅读