jquery 使用数组值对元素进行排序
我需要根据它的属性对一些元素进行排序。举个例子:
<div id="sort">
<div n="1"></div>
<div n="2"></div>
<div n="3"></div>
<div n="4"></div>
</div>
array_num
{3, 2, 1, 4}
伪代码:
$('#sort').sort(array_num, 'n');
结果将是:
<div id="sort">
<div n="3"></div>
<div n="2"></div>
<div n="1"></div>
<div n="4"></div>
</div>
I need to sort some elements depend on it attribute. For an example:
<div id="sort">
<div n="1"></div>
<div n="2"></div>
<div n="3"></div>
<div n="4"></div>
</div>
And array_num
{3, 2, 1, 4}
pseudo code:
$('#sort').sort(array_num, 'n');
results will be:
<div id="sort">
<div n="3"></div>
<div n="2"></div>
<div n="1"></div>
<div n="4"></div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此处有完整代码
Full code here
未经测试...
untested...
我偶然发现了这个,试图解决我所追求的问题。
我采用了 @shrikant-sharat 的方法并添加了一些内容,因为我需要排序的属性实际上位于子元素上。我想我会在这里添加,以防它对任何人(以及未来的我!)有帮助。
它允许您传递一个过滤器函数来匹配您想要的元素。我认为这不是最有效的,但它对我有用,例如:
I stumbled across this trying to fix what I was after.
I took @shrikant-sharat's method and added a little to it as the attribute I needed to sort on was actually on a child element. Thought I'd add here in case it helps anyone (and for future me!)
It allows you to pass a filter function to match the element you're after. It's not the most efficient I suppose, but it works for me, e.g.:
由于 jQuery 返回一个对象数组,您可以使用
sort
方法,然后按照新排序的顺序将子项“重新附加”到父项:Since jQuery returns an array of objects, you may use the
sort
method, and then 'reappend' the children to the parent in the newly sorted order: