che*_*ilM 6 javascript php ajax jquery jquery-select2
我通过AJAX在我的DOM中插入了几行概念(带有select和input文本元素).我想将那些select初始化为select2:但我不知道这样做的正确方法.
我在每个AJAX请求中都得到了这个:
<select id="concept0">
<option value="Test"> Test </option>
<option value="Test2"> Test 2 </option>
</select>
<script> $("#concept0").select2(); </script>
Run Code Online (Sandbox Code Playgroud)
但我认为在我的AJAX响应中使用HTML返回javascript是错误的想法.还有其他选择吗?
如果我的问题有点愚蠢,谢谢,对不起......
我会像这样构建流程:
我在这里做了一个模拟: http://jsbin.com/jotitu/edit?js, output
下面是一个小解释:
假设您有以下 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>
Run Code Online (Sandbox Code Playgroud)
如果您可以像这样分组并编写部分 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>
Run Code Online (Sandbox Code Playgroud)
我不会详细介绍,只需说:
$.get(conceptPartialUrl, successCallback);
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
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);
});
};
Run Code Online (Sandbox Code Playgroud)
var initSelect2Widgets = function(){
$containerEl.find('[data-widget="select2"]').select2();
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15688 次 |
| 最近记录: |