【问题标题】:select2 jquery plugin not working after ajax calling for HTML content changeajax调用HTML内容更改后select2 jquery插件不起作用
【发布时间】:2015-04-24 19:16:11
【问题描述】:

我确实为 html div 更改调用了 ajax 函数,在那个 div 更改内容中有 'select2' jquery 类来选择框。 ajax 加载后 select2 jquery 插件无法正常工作。

这是我的 js:

$('body').on('click', '.portlet > a.reloadcontent', function(e) {
   $.ajax({
      type: "GET",
      cache: false,
      url: url,
      dataType: "html",
      success: function(res) {
          $('#colpart').find('.portlet-body').html(res);
      }
   });
});

这是我的 HTML:

<div id="#colpart">
    <a href="#" data-url="columnspage.html" class="reloadcontent" data-load="true">Columns</a>
    <div class="portlet-body"></div>
</div>

columnspage.html

<select class="form-control select2me" data-placeholder="">
     <option value=""></option>
     <option value="1">Column 1</option>
 </select>

select2 jquery 插件的 select2me 类。

【问题讨论】:

标签: jquery html ajax jquery-select2


【解决方案1】:

你需要在成功回调后初始化select,因为你的下拉菜单是动态添加到DOM中的,

success:function(res){
   $('#colpart').find('.portlet-body').html(res);
   // reinit your plugin something like the below code.
   $('.select2me').select2();
}

【讨论】:

  • 尝试直接在页面中添加元素并调用它(不使用 ajax)并检查,不要忘记检查控制台是否有错误。
  • 在控制台显示“未捕获的异常:未为 Select2 s2id_autogen1 定义查询函数”
  • 我只需要通过ajax函数调用。
  • 好的,一旦你从静态页面调用它,你也可以用 ajax 来改变它。另请阅读此stackoverflow.com/questions/14483348/…
  • 我已经通过将类名删除到 id 名称来解决它。谢谢
【解决方案2】:

在ajax成功函数中需要初始化select。

例子:

    success: function (html) {
        // your code here
        $(".select2").select2(); // init the select
    }

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多