简体   繁体   English

根据值更改div的背景颜色

[英]Change background color of div based on a value

I am trying to make my basket button have a circular div background turn blue after an item is added to the basket, so far the add to basket function is working perfectly with ajax I just can't somehow toggle background from none to display based on for example if the basket has 1 or more items the background needs to be blue and if the basket has 0 items then background set to none, here is what I have tried so far: 我试图让我的篮子按钮有一个圆形div背景变成蓝色后,一个项目被添加到篮子,到目前为止添加到篮子功能是完美的与ajax我只是无法以某种方式切换背景从无显示基于例如,如果篮子有1个或更多项目,背景需要为蓝色,如果篮子有0个项目,那么背景设置为无,这是我到目前为止所尝试的:

if($objBasket->number_of_items > 0) {
    $background = "block";
} else {
    $background = "none";
}

?>
<p class="in-cart" style="background:<?php echo $background; ?>"><?php echo $objBasket->number_of_items; ?></p>

And the js: 和js:

function refreshMiniBasket() {

        $.ajax({

            url: '../modules/basket_mini_nav_refresh.php',
            dataType: 'json',
            success: function(data) {
                $.each(data, function(k, v) {
                    $(".in-cart").text(v);
                });
            },
            error: function(data) {
                alert('Error occurred');
            }

        });

    }

But this only changes the background state when I manually reload the page 但这只会在我手动重新加载页面时更改背景状态

Put the code for changing the background inside the success: of the Ajax call. 把改变背景的代码放在Ajax调用的success:之中。

        success: function(data) {
            $.each(data, function(k, v) {
                $(".in-cart").text(v);
            });

            // Update the JS variable that keeps track
            // of the number of items in the cart.

            // if that variable is > 0, set the background to blue.
            // else, set the background to transparent.
        },

This is more a job for javascript / jquery than php . 对于javascript / jqueryphp You can set the initial state of the basket in php, but should make live changes of the basket's state from javascript. 你可以在php中设置篮子的初始状态,但是应该从javascript中对篮子的状态进行实时更改。

Change your basket's look inside the successCallback of your ajax. 在ajax的successCallback中改变你的篮子外观。

function refreshMiniBasket() {
    $.ajax({
        url: '../modules/basket_mini_nav_refresh.php',
        dataType: 'json',
        success: function (data) {
            //...

            if (parseInt($(".in-cart").text()) > 0)
                $(".in-cart").show();
            else
                $(".in-cart").hide();
        },
        error: function (data) {
            //...
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM