如何使 Bootstrap 切换按钮在页面加载后启动并且在打开时不调用回调

How to make Bootstrap toggle button start on after page loads and not call callback if on

我一直在 Laravel 5 从事电子商务工作。在每个产品的详细信息页面中,我希望访问者单击切换按钮将该项目添加到购物车,然后再次单击以删除该项目。当我的访问者重新加载页面或稍后返回该产品的详细信息页面时,我希望该切换按钮在页面加载后启动 'on',以便我的访问者知道该产品已经在购物车中。我想使用切换按钮,因为它内置了元素的切换动画。我正在使用 Bootstrap Toggle 作为切换按钮元素。到目前为止我所做的是:

  1. HTML 按钮:

    <input id="btn_cart_item_toggle" type="checkbox" checked data-toggle="toggle" data-width="270" data-offstyle="danger" data-on="<i class='fa fa-shopping-cart'></i> Adicionar ao carrinho" data-off="<i class='fa fa-times'></i> Remover do carrinho" width="200" data-style="slow">
    
  2. 我将布尔值传递给控制器​​ (in_cart) 以判断产品是否已添加到购物车,所以我的 Blade 文件有:

    @if ($in_cart)
    $(document).ready(function() {
        $('#btn_cart_item_toggle').prop('checked', true).change();
        bootbox.alert('DEBUG: Product in cart');
    });
    @endif
    
  3. 紧接着,我有一些 jQuery 代码和 Blade 生成的东西来使用产品的 AJAX 调用(add/remove 来自购物车)身份证.

    $('#btn_cart_item_toggle').change(function () {
        if ($(this).prop('checked')) {
            $.post( "{{ route('api_cart_remove') }}", { id: '{{ $product->id }}' }, function(data) {
                if (data.success) {
                    $('span.cart-count').html(data.count);
                } else {
                    bootbox.alert('Fail');
                }
            });
        } else {
            $.post( "{{ route('api_cart_add') }}", { 'id': '{{ $product->id }}' }, function(data) {
                if (data.success) {
                    $('span.cart-count').html(data.count);
                } else {
                    bootbox.alert('Fail');
                }
            });
        }
    });
    

我无法在不调用回调的情况下启动切换按钮 'on'。使用 $('#btn_cart_item_toggle').prop('checked', true).change(); 回调函数被调用,我得到 "fail" 因为它试图在产品已经在购物车中时添加它。如果 $in_carttrue,我希望该按钮启动 'on' 而无需调用该函数。 我该怎么做?或者什么是更好的方法?

很难解释,因为它涉及很多东西,如 Blade、jQuery、CSS 和 Bootstrap,但我希望我足够清楚。

更新:

根据@CBroe 的评论,我设法让它按我想要的方式工作:

<input id="btn_cart_item_toggle" type="checkbox" data-toggle="toggle" @if (!$in_cart) checked @endif data-width="270" data-offstyle="danger" data-on="<i class='fa fa-shopping-cart'></i> Adicionar ao carrinho" data-off="<i class='fa fa-times'></i> Remover do carrinho" width="200" data-style="slow">

我不会在客户端执行此操作 – 而是编辑输出此输入元素的模板以包含 checked 属性开头(适用时)。

(这也应该使它“更快”,这意味着用户将在页面加载时看到正确的状态,而不仅仅是在 JS 运行 之后。)