首页 > 解决方案 > 带有select2的Jquery中继器无法正常工作

问题描述

我正在搜索关于这个问题的 2 天。

第一个元素运行良好。但重复元素后,前一个元素的 select2 字段会自动销毁。

中继器中有两个 rop div。当 ajax 请求选择第一个时,我将选项附加到值部分。

这是供参考的屏幕截图。

在此处输入图像描述

这是repeater和select2初始化的代码。

<script>
        $(function () {

            $(".attribute_list").on('change', ".attribute", function (e) {
                var attr_name = $(this).attr('name');
                var attr_id = $(this).val();
                $.ajax({
                    type: "POST",
                    url: "{{ route('products.getValue') }}",
                    headers: {
                        'X-CSRF-TOKEN': "{{ csrf_token() }}"
                    },
                    contentType: "application/json",
                    dataType: "json",
                    data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
                    success: function (data) {
                        var attribute_value = data.attribute_value;
                        var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';

                        if (attribute_value) {
                            $(field_name).empty();
                            $.each(attribute_value, function (key, value) {
                                $(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
                            });
                            // $(field_name).select2();

                        } else {
                            $(field_name).empty();
                        }
                    }
                });
            });
        });

    </script>
    <script>
        // $("#attribute_button").click(function(){
        //     $('#attribute_values').select2({
        //                 placeholder: "select attribute value"
        //             });
        // });
        window.onload = function () {
            $('.attribute_values').select2({
                placeholder: "select attribute value",
                allowClear: true
            });
        }

        $('.repeater').repeater({

            initEmpty: false,
            show: function () {
                $(this).slideDown();
                $('.attribute_values').select2({
                    placeholder: "select attribute value"
                });
            },

            hide: function (deleteElement) {
                if (confirm('Are you sure you want to delete this element?')) {
                    $(this).slideUp(deleteElement);
                }
            },

            ready: function (setIndexes) {
            },
        })

标签: javascriptjqueryjquery-select2repeater

解决方案


推荐阅读