我有一家基于 WooCommerce 的商店,我正在尝试根据用户操作实现一些事件跟踪。
我想在用户单击“下订单”按钮时运行自定义 JS 函数,这是付款前的最后一步。
这是按钮的代码:
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>
在我的脚本中,我有这个:
jQuery(document).ready(function ($) {
// here are some other handlers
$("#place_order").click(() => {
alert("click");
});
});
当我记录
$("#place_order")
的结果时,看来jQuery可以找到元素:a.fn.init [button#place_order.button.alt, context: document, selector: "#place_order"]
但是在 google chrome 的 devtools 窗口中,没有此按钮的单击处理程序(在事件监听器选项卡下),并且该功能未运行。
我在同一个 document.ready 函数中以类似的方式连接了其他点击事件,效果很好。
添加到购物车按钮:
<button type="submit" name="add-to-cart" value="2819" class="single_add_to_cart_button button alt">Add to cart</button>
脚本:
$("button[name=add-to-cart]").on("click", () => {
console.log("product added to cart"); // This works fine and visible under Event Listeners tab
});
我试过使用选择器
"button[name=woocommerce_checkout_place_order]"
和 .on("click")
也。那么我的下单按钮的事件监听器没有被添加或被删除的原因可能是什么?
有没有办法检查其他脚本是否从按钮中删除了处理程序?我在想也许 WooCommerce 出于某种原因将其删除。
最佳答案
至于结账“下单”提交 事件是 委托(delegate) 到<form>
通过 WooCommerce,您需要委托(delegate) 点击事件到<form>
也是这样:
jQuery(function($){
$('form.woocommerce-checkout').on( 'click', "#place_order", function(event){
event.preventDefault(); // Disable submit for testing
console.log("click");
alert("click");
});
});
或者嵌入在函数中的相同内容(定位结帐页面):
add_action('wp_footer', 'my_checkout_js_script');
function my_checkout_js_script() {
// Only on checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type='text/javascript'>
jQuery(function($){
$('form.woocommerce-checkout').on( 'click', "#place_order", function(event){
event.preventDefault(); // Disable submit for testing
console.log("click");
alert("click");
});
});
</script>
<?php
endif;
}
代码在您的事件子主题(或事件主题)的functions.php 文件中。
现在你会看到它有效。
相关:jQuery - Understanding Event Delegation
关于php - 为什么 jQuery 单击事件监听器未在 WooCommerce 按钮上注册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62133353/