在使用Woocomerce電商時,預設是沒有直接購買的按鈕。因為我們會透過Hook的方式改寫原本的頁面上的元素。
這次為了在可變商品,新增變動選擇時,沒有完全選取時,要disable立即購買按鈕。
就需要使用Elementor JS Hook來完成,這樣也可以不用透過setTimeout/setInterval的方法來輪詢元素是否前端widget已完成。
使用elementor/frontend/init來確認elementor的前端全域變數已載入
elementorFrontend 已初始化,可以開始監聽其他事件
$(window).on('elementor/frontend/init', function(){
console.log('[orca_woo_cart] Elementor frontend initialized');
// 可在這裡放入 elementorFrontend 相關監聽程式碼
if (typeof elementorFrontend !== 'undefined' && elementorFrontend.hooks) {
console.log('[orca_woo_cart] Elementor 已準備完成');
}
}
鎖定我們要處理的widget的hook
可以檢查原始碼可以發生data-widget_type的屬性
elementorFrontend.hooks.addAction('frontend/element_ready/woocommerce-product-add-to-cart.default', function($scope) {
console.log('[orca_woo_cart] WooCommerce Add to Cart widget 準備完成');
});
完成代碼
jQuery(function($){
console.log('[orca_woo_cart] cart-add-to-cart.js 載入');
$(window).on('elementor/frontend/init', function(){
console.log('[orca_woo_cart] Elementor frontend initialized');
// 可在這裡放入 elementorFrontend 相關監聽程式碼
if (typeof elementorFrontend !== 'undefined' && elementorFrontend.hooks) {
console.log('[orca_woo_cart] Elementor 已準備完成');
elementorFrontend.hooks.addAction('frontend/element_ready/woocommerce-product-add-to-cart.default', function($scope) {
console.log('[orca_woo_cart] WooCommerce Add to Cart widget 準備完成');
initBuyNowButton();
});
}
});
}