jQuery UI 获取 UL 中 LI 元素的排序位置
我正在使用 jQuery UI 的可排序功能来处理我的 UL 列表。每次用户对列表进行排序时,我希望每个 li 元素将其“position”属性更新为其在列表中的位置。
<ul>
<li position="1">a</li>
<li position="2">b</li>
<li position="3">c</li>
</ul>
因此,当用户将 c 与 a 交换时,位置也会更新。我尝试使用 .each 但似乎 javascript 不遵循 LI 元素显示的顺序,而是遵循元素创建的顺序。
I'm using jQuery UI's sortable for my UL list. Each time the user sorts the list, I want each li element to update it's "position" attribute to it's position in the list.
<ul>
<li position="1">a</li>
<li position="2">b</li>
<li position="3">c</li>
</ul>
So when a user swaps c with a, the position will also update. I tried to use .each but it seems that javascript doesn't follow the order of how the LI elements are displayed but the order of the element's creation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如另一个答案中提到的,使用
update
就是您所需要的:示例链接
As mentioned in another answer, using
update
is all you need:Example link
您是否尝试过 :eq 选择器或 index 方法?如果您知道要查找哪个 li 元素的位置,则可以像这样找到该位置:
Have you tried :eq selector or index method? Provided you know which li element you're trying to find the position of you could find the position like so:
您将需要利用可排序的“更新”事件:
然后您可以使用“序列化”方法来提取更新的项目顺序。要实现此功能,一个要求是每个列表项的 ID 都包含下划线,因此您需要将 HTML 更新为:
You'll want to take advantage of the Sortable "update" event:
You can then use the "serialize" method to pull the updated order of items. One requirement for this to work is that the IDs of each list item contain an underscore, so you'd want to update your HTML to: