javascript 如何动态初始化select2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32984078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:58:59  来源:igfitidea点击:

How to initialize select2 dynamically

javascriptphpjqueryajaxjquery-select2

提问by chemrailM

I insert rows of concepts (with select and input text elements) in my DOM through AJAX. And I want to initialice those select to select2: but I don't know the proper way to do that.

我通过 AJAX 在我的 DOM 中插入了多行概念(带有选择和输入文本元素)。我想将那些选择初始化为 select2: 但我不知道这样做的正确方法。

  • I should write the javascript in each row? (Insert html and JS through AJAX)
  • 我应该在每一行中编写 javascript 吗?(通过 AJAX 插入 html 和 JS)

I get this in each AJAX request:

我在每个 AJAX 请求中都得到了这个:

<select id="concept0"> 
    <option value="Test"> Test </option>
    <option value="Test2"> Test 2 </option>    
</select>
<script> $("#concept0").select2(); </script>

But I think is a wrong idea to return the javascript with the HTML in my AJAX response. There are other alternative?

但我认为在我的 AJAX 响应中返回带有 HTML 的 javascript 是一个错误的想法。还有其他选择吗?

Thanks and sorry if my question is a little stupid...

谢谢,对不起,如果我的问题有点愚蠢......

采纳答案by Tiberiu C.

I would construct the flow like this :

我会像这样构建流程:

  • Group the partials selects to reduce the number of Ajax requests
  • Add markers to the partial HTML with 'data-'
  • Retrieve partial html with AJAX GET;
  • Initialize elements;
  • [Optionally] Detach the target parent element - performance reasons;
  • Append elements to the target;
  • [Optionally] Reattach the target element;
  • Initialize the widgets.
  • 对部分选择进行分组以减少 Ajax 请求的数量
  • 使用“data-”向部分 HTML 添加标记
  • 使用 AJAX GET 检索部分 html;
  • 初始化元素;
  • [可选] 分离目标父元素 - 性能原因;
  • 将元素附加到目标;
  • [可选] 重新附加目标元素;
  • 初始化小部件。

I've made a simulation here : http://jsbin.com/jotitu/edit?js,output

我在这里做了一个模拟:http: //jsbin.com/jotitu/edit?js,output

Bellow is a little explanation:

波纹管是一个小解释:

So lets say you have the following HTML:

因此,假设您有以下 HTML:

<div id="concept-table-container">
 <table>
   <tr>
     <th>
        No.
     </th>
     <th>
        Name.
     </th>
     <th>
        Option.
     </th>
   </tr>
   <tr>
     <td>1</td>
     <td>abc</td>
     <td></td>
   </tr>
   <tr>
     <td>2</td>
     <td>dce</td>
     <td></td>
   </tr>
   <tr>
     <td>3</td>
     <td>fgh</td>
     <td></td>
   </tr>
 </table>
</div>

Group the partials selects to reduce the number of Ajax requests and add markers to the partial HTML with 'data-'

对部分选择进行分组以减少 Ajax 请求的数量,并使用“data-”向部分 HTML 添加标记

If you can group and write your partial HTML like this you won't need to do to an Ajax request for each row. You can chose to limit them also, but that requires a bit more programming for "pagination".

如果您可以像这样对部分 HTML 进行分组和编写,则不需要对每一行的 Ajax 请求进行处理。您也可以选择限制它们,但这需要更多的“分页”编程。

<select data-widget="select2" data-row-idx="0"> 
    <option value="Test"> Test </option>
    <option value="Test2"> Test 2 </option>    
</select>
<select data-widget="select2" data-row-idx="1"> 
    <option value="Test"> Test </option>
    <option value="Test2"> Test 2 </option>    
</select>
<select data-widget="select2" data-row-idx="2"> 
    <option value="Test"> Test </option>
    <option value="Test2"> Test 2 </option>    
</select>

Retrieve partial html with AJAX GET

使用 AJAX GET 检索部分 html

I won't get here into the details, it's enough to say that :

我不会在这里详细介绍,这样说就足够了:

$.get(conceptPartialUrl, successCallback);

Initialize elements;

初始化元素;

var successCallback = function(data){
  var $fragmentEl = initEls(data);
  // Optionally before appending the selects detach the container;
  appendElements($fragmentEl, $containerEl);
  // Initialize the widgets.
  initSelect2Widgets();
};


var initEls = function(data){
  // Create DOM elements - JQuery Way
  var $fragmentEl = $(data);
  // Return the reference
  return $fragmentEl;
};

Append elements to the target;

将元素附加到目标;

var appendElements = function($fragmentEl, $containerEl){
   var $rows = $containerEl.find('tr');
   $fragmentEl.each(function(){     
      var $el = $(this);


      // some matching - you 
      var idx = $el.data('row-idx');

      // that plus 1 is to skip the header        
      // find the row         
      var $row = $rows.eq(idx+1);         
      // find the cell, empty it and append the element  
      $row .find('td').last().text('').append($el);
   });
};

Initialize the widgets

初始化小部件

var initSelect2Widgets = function(){
  $containerEl.find('[data-widget="select2"]').select2();
};

回答by Harsh Makani

I have got another way around for this :

我有另一种解决方法:

As you said in your comment that you send a counter in each ajax request (I hope that you are using that counter to generate idof select), you can store that in some element or js variable before ajax request. So that at every ajax request you have that unique value of counter.

正如您在评论中所说,您在每个 ajax 请求中发送一个计数器(我希望您使用该计数器来生成id选择),您可以在 ajax 请求之前将其存储在某个元素或 js 变量中。因此,在每个 ajax 请求中,您都拥有计数器的唯一值。

Than you can initialize you select2 using :

比您可以使用以下方法初始化您的 select2:

$(document).ajaxComplete(function() {
    $(document).find('your-unique-counter-select-id').select2();
});