Javascript jqueryui:动态地将元素添加到排序表
我正在动态构建一个可排序列表,但是动态添加元素时,可排序列表的行为开始不正确:Javascript jqueryui:动态地将元素添加到排序表,javascript,jquery,jquery-ui,jquery-ui-sortable,Javascript,Jquery,Jquery Ui,Jquery Ui Sortable,我正在动态构建一个可排序列表,但是动态添加元素时,可排序列表的行为开始不正确: function buildHTML() { var selection = ['number', 'items', 'list']; var component = $('#selector'); component.empty(); for (var i = 0; i < selection.length; i++) { component.append('
function buildHTML() {
var selection = ['number', 'items', 'list'];
var component = $('#selector');
component.empty();
for (var i = 0; i < selection.length; i++) {
component.append('<li class="drag-button"> ' + selection[i] + '</li>');
}
component.sortable('refresh');
}
$('#selector').sortable({
tolerance: 'pointer',
cursor: 'move',
axis: 'x'
});
buildHTML();
这很奇怪。查看两个源之间的源看起来完全相同。一定是jQuery引擎罩下的某个东西不对 这可能不是您想要的答案,但它很有效,项目排序很快。一个简单的销毁,添加你的动态项目,然后重建:一切见小提琴
<ul id="selector">
<li class="drag-button">some</li>
<li class="drag-button">inital</li>
<li class="drag-button">stuff</li>
</ul>
<br/><br/><br/><br/>
<input type="button" value="Add some sortable items and rebuild it" onclick="reBuildIt()">
<script>
//this function will destroy, add your new items, then rebuild it
window.reBuildIt=function() {
var selection = ['number', 'items', 'list'];
var component = $('#selector');
component.sortable('destroy');
for (var i = 0; i < selection.length; i++) {
component.append('<li class="drag-button"> ' +
selection[i] +
'</li>');
}
$('#selector').sortable({ tolerance: 'pointer', cursor: 'move', axis: 'x' });
}
//show any initial sortable items
$('#selector').sortable({ tolerance: 'pointer', cursor: 'move', axis: 'x' });
</script>
我发现它与空的有关。当我在HTML中添加a时,它似乎可以正常工作。所以,在初始化时,sortable可能会缓存一些变量,而在刷新时不会更新这些变量!
<ul id="selector">
<li class="drag-button">some</li>
<li class="drag-button">inital</li>
<li class="drag-button">stuff</li>
</ul>
<br/><br/><br/><br/>
<input type="button" value="Add some sortable items and rebuild it" onclick="reBuildIt()">
<script>
//this function will destroy, add your new items, then rebuild it
window.reBuildIt=function() {
var selection = ['number', 'items', 'list'];
var component = $('#selector');
component.sortable('destroy');
for (var i = 0; i < selection.length; i++) {
component.append('<li class="drag-button"> ' +
selection[i] +
'</li>');
}
$('#selector').sortable({ tolerance: 'pointer', cursor: 'move', axis: 'x' });
}
//show any initial sortable items
$('#selector').sortable({ tolerance: 'pointer', cursor: 'move', axis: 'x' });
</script>