【问题标题】:on change after append new select2追加新select2后更改
【发布时间】:2020-08-01 05:48:44
【问题描述】:

我正在使用 select2,我想处理更改事件

第一次效果很好,但是当我在每次更改后附加新的 select2 并且在更改后附加新的 select2 后不起作用

$('select').on("select2:select", function(e) {
    e.preventDefault();
    var item_id = $("option:selected").data('id');
    var product_id = $("option:selected").data('product');
    $.ajax({
        type: "post",
        url: window.location.origin + '/product/get-items',
        data: {
            item_id: item_id,
            product_id: product_id,
            "_token": $('#csrf-token')[0].content //pass the CSRF_TOKEN()
        },
        success: function(data) {
            $(".all-items").hide();
            data.specifications.forEach(myFunction);

            function myFunction(specification, index) {
                var a = '<div class="all-items"><div class="mb-1"><div class="row py-1"><label style="font-size: 16px; margin: 10px; margin-bottom: 10px" class="py-1 mt-2">' + specification.name + ' :</label></div><div class="row"><select class="js-example-basic-single select-' + index + ' test' + index + ' item selectpicker selectItem" name="specification[]"> </div></div></div>';
                $(".all").append(a);

                specification.items.forEach(test);

                function test(value, inx) {
                    if (data.itemIds.includes(value.id.toString())) {
                        var a = '<option style="font-size: 10px" data-id="e" data-product="dd" value="dd">' + value.name + '<span></span></option></select>';
                        $(".test" + index).append(a).select2();

                    }
                }
            }
        }
    });
});

我必须添加部分 首先,追加 select2 并在此之后追加每个选择的选项

我想对所有 select2(追加和初始)使用更改事件

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    查询选择器$('select') 仅收集文档中的当前 选择元素,不包含附加到文档的后续元素。所以你需要使用更通用的选择器来覆盖后期元素。这应该有效:

    $(document).on("select2:select","select",function(e) { })
    

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 1970-01-01
      • 2019-07-15
      • 2022-11-21
      • 1970-01-01
      • 2012-06-09
      • 2020-02-15
      • 1970-01-01
      • 2014-07-06
      相关资源
      最近更新 更多