使用jQuery显示列表项的索引 [英] Display index of list item using jQuery

查看:80
本文介绍了使用jQuery显示列表项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的无序列表:

I have an unordered list like so:

<ul class="foo">
  <li id="asdf">
    <span class="indexnumber"></span>
    <span class="description">whatever</span>
  </li>

  <li id="asdfasdf">
    <span class="indexnumber"></span>
    <span class="description">whatever</span>
  </li>
</ul>

我想在indexnumber范围内显示列表项的索引号(即,第一个项目将显示1,第二个项目将显示2,依此类推).我的用户将能够对列表项进行排序(使用jQuery ui sortable).我希望能够在列表项中向用户显示一个数字,以指示该列表项的位置(该值可以随着用户对列表进行重新排序而改变).

I want to display the index number of the list item in the indexnumber span (i.e., the first item will display 1, the second will display 2, and so on). My users will have the ability to sort the list items (using jquery ui sortable). I would like to be able to show my users a number in the list item that indicates where the list item is (and the value can change as the user re-orders the list).

如何使用jquery简单地显示数组中的索引位置?或者,是否有一种简单的方法可以对可排序事件进行处理(即,一旦对列表进行了排序,则在适当时对所有其他列表项中的索引号进行递增或递减)?

How can I simply display the index position in the array using jquery? Alternately, is there an easy way to do this with the sortable events (i.e., once the list is sorted, increment or decrement the indexnumbers in all other list items as appropriate)?

推荐答案

我最终做了以下事情:

$(function() {
    $(".foo").sortable({
        stop: function(event, ui) {
            var itemID = $(ui.item).attr("id");
            var items = $("li#" + itemID).parent(".foo").children();

            var updateditems = new Array();

            for (var i = 0; i <= items.length - 1; i++) {
                var singleitemID = $(items[i]).attr("id");
                var loc = i + 1;

                $("#" + singleitemID).text(loc);


                updateditems.push([singleitemID, loc]);
            }
        }
    });
});

这篇关于使用jQuery显示列表项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆