簡體   English   中英

根據值更改div的背景顏色

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

我試圖讓我的籃子按鈕有一個圓形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>

和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');
            }

        });

    }

但這只會在我手動重新加載頁面時更改背景狀態

把改變背景的代碼放在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.
        },

對於javascript / jqueryphp 你可以在php中設置籃子的初始狀態,但是應該從javascript中對籃子的狀態進行實時更改。

在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