在不丢失事件处理程序的情况下对元素列表进行排序
我有 this 列表:
<ul>
<li id="6">
list 6: somethings
</li>
<li id="2">
list 2: somethings
</li>
<li id="4">
list 4: somethings
</li>
<li id="5">
list 5: somethings
</li>
<li id="0">
list 0: somethings
</li>
</ul>
我想(使用 Javascript/jQuery)按 id 对这些元素进行排序(ASC )保留每个元素的事件处理程序。
是否可以?我该怎么做呢?
I have this list :
<ul>
<li id="6">
list 6: somethings
</li>
<li id="2">
list 2: somethings
</li>
<li id="4">
list 4: somethings
</li>
<li id="5">
list 5: somethings
</li>
<li id="0">
list 0: somethings
</li>
</ul>
and I'd like (with Javascript/jQuery) order these elements by the id (ASC) keeping the event handler for each element.
Is it possible? How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将 ID 分配到一个数组中并使用
sort()
:您永远不会从列表中删除它们,而只是移动它们。点击处理程序保持不变:
http://jsfiddle.net/niklasvh/nVLqR/
You could just assign the ID's into an array and use
sort()
:You are never removing them from the list, just moving them around. Click handler stays intact:
http://jsfiddle.net/niklasvh/nVLqR/
这应该可以正常工作。使用
detach
保留与该元素关联的所有事件。然后,您可以使用自定义排序函数来比较每个li
元素的id
属性。请参阅此处的小提琴示例。单击事件附加到 ID 为“6”的
li
。列表重新排序后,仍会处理该单击事件。This should work fine. Using
detach
preserves any events associated with the element. You then use a custom sort function to compare theid
attributes of eachli
element.See an example fiddle here. A click event is attached to the
li
with ID "6". After the list has been reordered, that click event is still handled.我认为要订购它们,您必须将它们删除并添加回 DOM 中……因此您肯定会丢失事件处理程序。您是否可以控制处理程序,可以重新绑定或使用
live()
来代替吗?另一种方法是绝对定位
li
元素并使用 css 位置属性(top
、right
、bottom
,left
) 来移动它们,这将使它们在 DOM 中保持相同的顺序,但按照您想要的顺序渲染它们。tI think to order them you'll had to remove and add them back into the DOM... and therefore you'll certainly lose the event handler. Are you in control of the handler, can you rebind or use
live()
instead?The alternative would be to absolutely position the
li
elements and use the css position properties (top
,right
,bottom
,left
) to move them around, this will keep them in the same order in the DOM, but render them in your desired order.t这个例子对我有用:
或者如果你想与其他信息一起排序:
This example work for me:
or if you want to sort with other informations: