我在 localhost 上使用带有 Hello Elementor 主题的 WooCommerce,并且我有几个用于产品变体的自定义字段。当不满足特定依赖条件时,我想隐藏变体。...
我在 localhost 上使用带有 Hello Elementor 主题的 WooCommerce,并且我有几个用于产品变体的自定义字段。当不满足特定依赖项条件时,我想隐藏变体。我使用以下 jQuery 代码来检查依赖项并切换可见性:
$('#product-variants .variant-card').each(function () {
const $variant = $(this);
const dependencies = ($variant.data('dependencies') || '').split(',').filter(Boolean);
const allDependenciesMet = dependencies.every(dependencyIndex => {
const dependentVariant = $('[data-variant-index="' + dependencyIndex + '"]');
const quantity = parseInt(dependentVariant.find('input[type="range"]').val(), 10) || 0;
return quantity > 0; // Check if quantity is more than 0
});
if (!allDependenciesMet) {
$variant.hide(); // Hide variant if dependencies are not met
} else {
$variant.show(); // Show variant if all dependencies are met
}
});
问题是,当页面加载时,变体首先正确隐藏,但随后显示属性几乎立即(不到一秒)快速变回阻止,导致变体重新出现。
我没有使用任何其他可能干扰此逻辑的插件,只有 woocommerce 安装在我的本地主机上。
任何见解或解决方案都将不胜感激!
尝试使用 MutationObserver
来监视 DOM 的变化,并确保在发生更改时重新应用可见性逻辑。类似于:
$(document).ready(function () {
function checkDependencies() {
$('#product-variants .variant-card').each(function () {
const $variant = $(this);
const dependencies = ($variant.data('dependencies') || '').split(',').filter(Boolean);
const allDependenciesMet = dependencies.every(dependencyIndex => {
const dependentVariant = $('[data-variant-index="' + dependencyIndex + '"]');
const quantity = parseInt(dependentVariant.find('input[type="range"]').val(), 10) || 0;
return quantity > 0; // Check if quantity is more than 0
});
if (!allDependenciesMet) {
$variant.hide(); // Hide variant if dependencies are not met
} else {
$variant.show(); // Show variant if all dependencies are met
}
});
}
// Initial check
checkDependencies();
// Monitor changes in the product-variants container
const targetNode = document.getElementById('product-variants');
const config = { childList: true, subtree: true, attributes: true };
const callback = function (mutationsList, observer) {
checkDependencies();
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
});