在jQuery Sort之后获取更新的顺序
Get updated order after jQuery Sort
我正在使用jQuery UI的Sortable对一些列表项进行重新排序。我想根据排序后的更新顺序更新每个 li 的类。这是我的网页:
<ul id="sortable">
<li class="1">apple</li>
<li class="2">orange</li>
<li class="3">pear</li>
<li class="4">peach</li>
</ul>
我想要实现的是,在苹果上方对梨进行排序后,我的课程更新如下:
<ul id="sortable">
<li class="1">pear</li>
<li class="2">apple</li>
<li class="3">orange</li>
<li class="4">peach</li>
</ul>
这个JSFiddle接近我所追求的,但我想更新类而不是html:http://jsfiddle.net/4mcpq/3/
由于改变一个li
的位置会改变所有其他li
的class
,实现此目的的唯一合理方法是迭代.sortable
update
回调中的li
元素:
"update": function (event, ui) {
$(this).children().each(function (i, elem) {
var li = $(elem), // cache lookup
cssClass = elem.className.split(' ').filter(function (name, i, array) {
return /^js[-]'d+$/g.test(name);
}).join(''); // adding .join('') to transform to string
// classes cannot start with a number (see http://www.w3.org/TR/CSS21/grammar.html#scanner).
// using pattern of "js-#" for the custom class
$(elem).removeClass(cssClass).addClass('js-' + i);
});
}
工作演示:http://jsfiddle.net/4mcpq/210/
警告:如果您有数千个li
元素,这可能会降低您的 UI 速度。有更简单(和更明智)的方法可以获得正确的目标li
具体取决于您要执行的操作。
为什么不在 css 中使用像 nth-child() 选择器这样的东西。
例如:
#sortable li:nth-child(1) {
/*insert your style for the first child here*/
}
#sortable li:nth-child(2) {
/*insert your style for the second child here*/
}
所以我发现我可以使用 .index() 来查找更新的排序顺序。然后我可以将每个 li 的类设置为它的索引。
$("#sortable").sortable({
update: function(event, ui) {
$("#sortable li").each(function() {
$(this).removeClass();
var $index = $(this).index();
$(this).prop("class", $index);
});
}
});
看到这个小提琴:http://jsfiddle.net/2f9vkhxj/8/
相关文章:
- Javascript循环不会自我更新
- 添加文字和评论功能更新Div
- ajax请求的顺序总是不同的
- 按照选项卡索引的顺序循环一个jQuery选择
- AngularJS:ng之后,重复$scope值未按预期更新
- 如何通过数组更新角度子范围
- Ajax更新表数据,但不重复顺序
- 如何在主干中对列表进行排序时更新模型的顺序属性
- 在具有交互性的酒窝多系列图表中更新系列顺序
- 更改图像的顺序并在数据库中更新
- 在MongoDB中更新后,插入项目的顺序搞砸了
- 在jQuery Sort之后获取更新的顺序
- 根据数字排序顺序更新自动重新排列HTML列表
- 在backbone.js中,如何使用新的模型数据更新视图,同时在没有完整渲染的情况下保持排序顺序
- 更新数据时保留和提示排序顺序
- Splice()不更新knockout.js中数组的项顺序
- 使用AJAX的Ruby on Rails更新列表打破了顺序
- 使用Jquery sortable和gridview更新排序顺序
- 使用jquery更新列表顺序
- 用用户输入的信息更新表,使表按字母顺序显示数组值