简体   繁体   English

更改添加到购物车的背景颜色

[英]Change background color of add to cart

I have cart page where i am showing different items 我在购物车页面上显示不同的商品

@foreach($model_parts as $key=>$val)
<div class="col-md-6">
   <!-- <pre>{{  print_r($val->toArray())}}</pre>  -->
    <div class="product-box">
        <div>{{$val['repair']['parts_name']}}</div>
        <div>{{$val['parts_price']}}</div>
        <div><button class="btn btn-info " id="togglebutton_{{$val['id']}}" onclick="addToCart({{$val['id']}})">Add to Cart</button></div>
    </div>
</div>
@endforeach

When user click on add to cart button then background need to change 当用户点击添加到购物车按钮时,背景需要改变

Here is my AJAX call 这是我的AJAX电话

function addToCart(product) {
    $.ajax({
        type: 'POST',
        url: base_url + 'myteam/add-to-cart',
        data: {parts_name: product, _token: "{{ csrf_token() }}"},
        success: function (data) {
            console.log(data);
            $('body').load(location.href + "#cart-list");

            if (data.type == 'new' && data.msg == 'success') {
                setTimeout(function () {
                    $('#togglebutton_' + data.classStyles).addClass('darkProduct');
                }, 200);
            }
            if (data.type == 'already_exist' && data.msg == 'success') {
                setTimeout(function () {
                    $('#togglebutton_' + data.classStyles).removeClass('darkProduct').addClass('noProduct');
                }, 200);

            }
        }
    });
}

Each time user click on add to cart button product will be kept in session and now I can able to set color for last added cart because of page refresh . 每次用户单击“添加到购物车”按钮产品都会保留在会话中,现在由于页面刷新,我可以为最后添加的购物车设置颜色。

You can checked if button is clicked or not and based on that you can change the css as required. 您可以检查是否单击了按钮,然后可以根据需要更改css。

 $("#buttonid").click(function(){
        if(clicked){
            $(this).css('background-color', 'red');
            clicked  = false;
        } else {
            $(this).css('background-color', 'blue');
            clicked  = true;
        }   
    });

You could do it like this instead 你可以这样做

$("#buttonid").click(function(){
    var color = clicked ? 'red' : 'blue';
    $(this).css('background-color', color);
    clicked = !clicked;
});

We move the color picking to a single variable choice using a ternary statement and then we only have to write out the change to the CSS of the element once. 我们使用三元语句将颜色选择移动到单个变量选择,然后只需将更改写出到元素的CSS一次即可。 then we flip the boolean. 然后我们翻转布尔值。

use jquery css() method. 使用jquery css()方法。

function addtocart(){   
 $("#buttonid").css("background-color", "red");//change the background color of button to Red
    var clr="red";
}

add the above code in the onclick function., and then 将上述代码添加到onclick函数中,然后

$(document).ready(function(){
$("#buttonid").css("background-color", clr);
})

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

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