[英]Call a function from enqued js file on wordpress
我已將 JS 文件排隊到我的 WordPress 插件中,使用:PHP
public function enqueue_scripts() {
wp_enqueue_script('my_awesome_plugin', plugins_url( '../assets/main.js', __FILE__), NULL, NULL, true );
}
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
我在該文件上有一個名為 addedToCart() 的 function:JS
addedToCart(){
console.log("Added to Cart");
}
一旦用戶添加到他的購物車,我需要調用它 function。 我可以使用這個鈎子:PHP
add_action( 'woocommerce_add_to_cart', array( $this, 'add_to_cart' ), 10, 6 );
public function add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
?>
<script>
//What code should I add <-- Line
<script>
<?PHP
}
我應該寫什么代碼來調用 JS 文件上的 function?
謝謝你的時間。
可以通過監聽 Woocommerce Js 事件來實現:
jQuery(document).ready(function($){
$('body').on( 'added_to_cart', function(){
//alert("Added to cart");
addedToCart(); //your function
});
});
以下是圍繞添加到購物車場景可用的事件列表:
$( document.body ).trigger( 'adding_to_cart', [ $thisbutton, data ] );
$( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'removed_from_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'wc_cart_button_updated', [ $button ] );
$( document.body ).trigger( 'cart_page_refreshed' );
$( document.body ).trigger( 'cart_totals_refreshed' );
$( document.body ).trigger( 'wc_fragments_loaded' );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.