WordPress/WooCommerce中jQuery after重复添加div问题求助
解决jQuery在WooCommerce中重复添加元素的问题
问题分析
你的代码里,选择器.order_item .woocommerce-Price-amount, .is-well .woocommerce-Price-amount匹配到了2个DOM元素(或同一个元素被两次命中),导致.after()方法执行两次,重复插入了新div。哪怕确认jQuery只加载一次、代码不在循环内,只要选择器命中多个元素,就会出现重复添加的情况。
解决方案
1. 优化选择器,精准匹配目标元素
先排查选择器命中的元素数量:打开浏览器控制台,执行以下命令:
$(".order_item .woocommerce-Price-amount, .is-well .woocommerce-Price-amount").length
如果返回2,说明需要调整选择器,只保留能唯一匹配目标元素的规则:
- 若目标元素仅属于
.order_item的后代,简化选择器:
$(".order_item .woocommerce-Price-amount").after( '<div class="price-wrapper eur"><div class="price">' + someVar + "</div></div>" );
- 若存在元素同时被两个选择器命中,用
:not()排除重复:
$(".order_item .woocommerce-Price-amount, .is-well .woocommerce-Price-amount:not(.order_item *)").after( '<div class="price-wrapper eur"><div class="price">' + someVar + "</div></div>" );
2. 添加前清理已存在的元素
如果页面可能动态加载内容,或者需要保留原选择器但只添加一次,可以先移除已存在的目标div,再执行添加:
jQuery(document).ready(function($) { var someVar = $(".product-total .woocommerce-Price-amount").html(); // 先移除已添加的重复元素 $(".price-wrapper.eur").remove(); // 再插入新元素 $(".order_item .woocommerce-Price-amount, .is-well .woocommerce-Price-amount").after( '<div class="price-wrapper eur"><div class="price">' + someVar + "</div></div>" ); });
3. 确保代码仅执行一次
如果是wp_footer钩子被多次触发(WordPress部分场景下可能出现),可以在PHP层面限制函数只执行一次:
add_action('wp_footer', 'myFunction'); function myFunction() { static $has_run = false; if ($has_run) return; $has_run = true; ?> <script> jQuery(document).ready(function($) { var someVar = $(".product-total .woocommerce-Price-amount").html(); $(".order_item .woocommerce-Price-amount, .is-well .woocommerce-Price-amount").after( '<div class="price-wrapper eur"><div class="price">' + someVar + "</div></div>" ); }) </script> <?php }
或者用jQuery的.one()方法确保代码仅执行一次:
jQuery(document).one('ready', function($) { var someVar = $(".product-total .woocommerce-Price-amount").html(); $(".order_item .woocommerce-Price-amount, .is-well .woocommerce-Price-amount").after( '<div class="price-wrapper eur"><div class="price">' + someVar + "</div></div>" ); });
内容的提问来源于stack exchange,提问作者alench
相关产品推荐
相关产品推荐

