javascript - 在 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。呸骗子!
那么我该如何解决呢?
我可以覆盖 WooCommerce
./cart/cart.php
-模板并将类添加到模板中。添加课程似乎有点矫枉过正。我可以每秒(左右)扫描 DOM 中的表并应用表类,如果它不存在的话。不酷......不管它是使用 jQuery 还是 Vue 完成的。
由于整个表在 DOM 中被替换,因此监视当前表(在 Vue 中使用 watch(){...} )并在它发生变化时应用类,因为它永远不会改变(它是替换)。
我找不到可以使用的 Hook。
我也尝试过使用ajaxComplete
,但我可以在网络选项卡中看到 XHR 请求正在触发,但这里的代码从不做任何事情(在控制台中):
jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
console.log( 'Test' );
});
还有其他建议吗?
解决方案
您可以使用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>
推荐阅读
- node.js - NodeJS - 如何在 Windows 10 上正确安装和运行 Webpack?
- c# - 如何在 Visual Studio 2017 中查找派生类?
- ios - 配置文件不包括 aps-evironmentProd、Xcode 10.1
- c# - 如何在 C# 中同步等待事件的结果?
- python - 分水岭分割不包括单独的对象?
- vuejs2 - Vuejs Computed Property 警告我没有设置器
- r - jsonlite 和 rjson 包之间的根本区别是什么?
- node.js - docker找不到本地nodejs模块
- python - 基于交互式参数值存储函数的输出
- c - 从C中的无符号整数末尾抓取'n'二进制位?位掩蔽?