gpt4 book ai didi

php - 当 woocommerce 购物车为空时将类添加到 div

转载 作者:行者123 更新时间:2023-11-27 22:42:42 26 4
gpt4 key购买 nike

我想向包含购物车数量的元素添加一个类(或直接设置样式),仅当购物车为空时。

下面是我目前使用的代码,效果很好。购物车计数效果很好,但颜色没有更新。

header.php(在菜单中的购物车图标后添加购物车计数)

?>          
<div class="counter_bubble">
<a href="/cart">
<span class="counter" id="cart-count"><?php
$cart_count = WC()->cart->get_cart_contents_count();
echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
?></span>
</a>
</div>
<?php

functions.php(排队自定义 javascript + 购物车刷新)

// ADD CUSTOM JS FILE FROM CHILD THEME
add_action('wp_enqueue_scripts', 'bubblescript');

function bubblescript() {
wp_enqueue_script( '_tandt-main', get_template_directory_uri() .
'/../Graffont/js/gft-script.js', array("jquery"), $my_js_ver, true );
}

// REFRESH CART FRAGMENTS (ITEM COUNT) SO CORRECT NUMBER IS ALWAYS SHOWN
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_cart_count', 50, 1 );

function refresh_cart_count( $fragments ){
ob_start();
?>
<span class="counter" id="cart-count"><?php
$cart_count = WC()->cart->get_cart_contents_count();
echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
?></span>
<?php
$fragments['#cart-count'] = ob_get_clean();

return $fragments;
}

gft-脚本.js

jQuery(document).ready(function($) {

function changecartbubble() {
if ($('body').find('#cart-count').length > 0) {
if (parseInt($('#cart-count').html()) > 0) {
// cart has number > 0 so cart has items
//change background class
$('#cart-count').addClass('other-background-of-bubble');
}
else {
// cart has no number so cart has no items
//remove background class
$('#cart-count').removeClass('other-background-of-bubble');
}
}
}

});

style.css - 当前 CSS

.counter {
background-color: #ff0;
border-radius: 20px;
font-size: 10px;
padding: 0 4px 0 4px;
}

.other-background-of-bubble{
background-color:red!important;
}

最佳答案

您可以在文档准备就绪时调用此函数,并且只要通过 ajax 更新购物车。

Javascript/jQuery:

function changecartbubble() {
if ($('body').find('#cart-count').length > 0) {
if (parseInt($('#cart-count').html()) > 0) {
// cart has number > 0 so cart has items
//change background class
$('#cart-count').addClass('other-background-of-bubble');
}
else {
// cart has no number so cart has no items
//remove background class
$('#cart-count').removeClass('other-background-of-bubble');
}
}
}

风格:

.other-background-of-bubble{
background:red!important;
}

关于php - 当 woocommerce 购物车为空时将类添加到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59743071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com