Zet*_*eth 6 javascript jquery woocommerce
WooCommerce桌带有这样的班,开箱即用:shop_table shop_table_responsive cart woocommerce-cart-form__contents。所以没有table-class,这意味着没有漂亮的Bootstrap表。
!
并且由于仅在绝对必要时才应覆盖WooCommerce模板,因此让我们使用JavaScript来解决它!
我的整个网站都由Vue-div封装,如下所示:
<div id="app">
...
<table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents">
...
...
</table>
...
</div>
Run Code Online (Sandbox Code Playgroud)
因此,最初,我编写了以下代码,将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' );
}
}
}
Run Code Online (Sandbox Code Playgroud)
...将其放在- mounted(){ ... }节中。
可行!到目前为止,一切都很好。
但是WooCommerce大量使用jQuery。在购物车页面上,如果我更改数量(然后按“更新”),则使用AJAX更新表内容。如果您好奇它是如何工作的,则可以在此处查看。
并且当运行时,我假设WooCommerce获取了初始的购物车模板并重新加载了整个表格。没有新添加的table-class。呸骗子!
那么我该如何解决呢?
我可以覆盖WooCommerce ./cart/cart.php-template并将类添加到模板。似乎添加类过多了。
我可以每秒(或大约)扫描DOM查找表,并应用表类(如果不存在的话)。不酷...无论使用jQuery还是Vue完成。
由于整个表已在DOM中替换,因此监视当前表(在Vue中使用watch(){...})并在其更改时应用该类是行不通的,因为它永远不会更改(替换)。
我找不到可以使用的挂钩。
我也尝试使用ajaxComplete,但是我可以在网络选项卡中看到XHR请求正在触发,但是这里的这段代码从不执行任何操作(在控制台中):
jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
console.log( 'Test' );
});
Run Code Online (Sandbox Code Playgroud)
还有其他建议吗?
您可以使用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);Run Code Online (Sandbox Code Playgroud)
<div id="some-id">(container)</div>
<button>change</button>Run Code Online (Sandbox Code Playgroud)