【问题标题】:jQuery Select2 plugin on dynamicaly loaded div动态加载的 div 上的 jQuery Select2 插件
【发布时间】:2018-10-06 07:33:25
【问题描述】:

我尝试加载一个带有 select2 插件的列表框的 div。 以下代码用于 div 容器

<div class="form-body">
    <div class="form-group">
        <?php echo lang('project_product', 'product', array('class' => 'col-sm-2 control-label')); ?>
        <div class="col-sm-2">
            <select id="id_product" name="id_product" tabindex="4" class="form-control select2 id_product"></select> 
        </div>
    </div>       

    <div class="form-actions pull-right">
        <a href="javascript:;" id="cancel_product" class="btn btn-default">
            Cancel
        </a>&nbsp; 
        <a href="javascript:;" id="add" class="btn btn-success">
            <i class="fa fa-plus"></i> Add product
        </a>            
    </div> 
</div>   

div 容器由按钮上的点击事件加载:

$(document).on('click', '#add_product', function(e){
    $('#add_p_container').removeClass('hide');
    $('#add_p_container').load(JS_BASE_URL + 'admin/projects/add_product/' + id_project);       
});

问题是,如果我从下面的 js 文件中加载 jQuery,其中#add_product 的点击事件,select2 将不起作用。

我用来初始化select2的代码:

$("#id_product").select2({
    minimumInputLength: 2,
    placeholder: "Select a product",
    allowClear: true,
    quietMillis: 100,
    ajax: {
        url: JS_BASE_URL + 'admin/products/productsList',
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (params) {
          return {
            q: params.term, // search term
            page: params.page
          };
        },
        processResults: function (data, params) {
          // parse the results into the format expected by Select2
          // since we are using custom formatting functions we do not need to
          // alter the remote JSON data, except to indicate that infinite
          // scrolling can be used
          params.page = params.page || 1;

          return {
            results: data,
            pagination: {
              more: (params.page * 30) < data.total_count
            }
          };
        },
        cache: true
    },
    escapeMarkup: function(markup) {
        return markup;
    } // let our custom formatter work

}); 

如果我在div中加载select2时直接从上面加载它,我会收到错误:

 [Show/hide message details.] SyntaxError: expected property name, got end of script

有没有人知道如何解决这个问题?谢谢!

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    在尝试寻找解决问题的方法后,似乎将脚本加载到 div 中会起作用,但会删除所有 cmets 我不知道为什么,但它确实有效

    所以,请确保您不要留下任何 cmets,否则它将无法正常工作

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多