如何计算属性总和[Laravel]

问题描述

每台台式计算机都可以选择适当的组件,例如:Ram,图形卡等。

  1. 每个组件都有其各自的价格

  2. (如果用户选择组件)。价格应根据选择动态显示。

照片: https://i.stack.imgur.com/VhZ54.png

价格应如何累加?

感谢您的帮助。

刀片HTML:

                @if($product->values)

            <!-- Product controls -->
            <div class="product-controls">
                <!-- Price -->
                <div class="columns">
                    
                    <div class="column is-4">

                        <div class="heading is-invisible">Konfigurator:</div>
                        <div class="value is-size-6" style="white-space: nowrap;">Wybierz konfigurację:</div>
                        
                    </div>

                    @foreach($product->values as $value)

                        <div class="column">
                            <div class="heading has-text-weight-semibold">{{ App\Models\Option::find($value->option_id)->name }}</div>

                            <div class="select">
                                <select>
                                    <option value="{{ $value->id }}" price="{{ $value->price }}">{{ $value->name }}
                                        <span class="has-text-danger">(price: +{{ $value->price }})</span>
                                    </option>
                                </select>
                            </div>

                        </div>
                    @endforeach
                </div>
            </div>

            @endif

刀片JS:

@section('footer')

    <script>
    $(document).ready(function(){
        $('option[value]').change(
        function(){
            var total = Number($('#new-price').attr('price'))+Number($('option[value]:selected').attr('price'));

            $('#new-price').html(total.toFixed(2)+' zł');

        });
    });
    </script>

    <script src="/assets/js/shop/product.js"></script>
    @stop

解决方法

您需要对所有value中的class="select"求和(我会考虑重命名class="product-select")。

您可以这样做:

$(".product-select").on('change',function () {
    let total = $(".product-select").reduce(function (total,select) {
        if (select.val()) {
            let option = select.find('option[value="'+select.val()+'"]');
            total += Number.parseFloat(option.attr('price'));
        }

        return total;
    },0);

    $('#new-price').html(total.toFixed(2)+' zł');
});
,

使用属性“ data-price”,通常会在日志控制台中显示价格值,但是现在如何对其进行汇总?

<script type="text/javascript">

$('#product-select').on('change',function() {
    var option = $(this).find('option:selected');
    console.log(option.data('price'));

    $('#new-price').html(total.toFixed(2)+' zł');

});

</script>

照片: https://i.stack.imgur.com/OXsyE.jpg

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...