根据属性“数据排序”对 jQuery 中的 div 进行排序?
如果我有几个 div:
<div data-sort='1'>div1</div>
<div data-sort='4'>div4</div>
<div data-sort='8'>div8</div>
<div data-sort='12'>div12</div>
<div data-sort='19'>div19</div>
并且我动态创建 div:
<div data-sort='14'>div1</div>
<div data-sort='6'>div1</div>
<div data-sort='9'>div1</div>
如何让它们按顺序排序到已加载的 div,而不必重新加载所有 div?
我认为我需要构建屏幕上所有 div 的数据排序值的数组,然后查看新 div 的位置,但我不确定这是否是最好的方法。
If I have several divs:
<div data-sort='1'>div1</div>
<div data-sort='4'>div4</div>
<div data-sort='8'>div8</div>
<div data-sort='12'>div12</div>
<div data-sort='19'>div19</div>
And I dynamically create the divs:
<div data-sort='14'>div1</div>
<div data-sort='6'>div1</div>
<div data-sort='9'>div1</div>
How can I get them to just sort into the divs already loaded in order, without having to reload all of the divs?
I think that I would need to build an array of the data-sort values of all of the divs on the screen, and then see where the new divs fit in, but I am not sure if this is the best way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用这个函数
你可以在添加新的div之后调用这个函数。
如果您想在 div 中保留 javascript 事件,请不要使用 html 替换,如上面的示例所示。而是使用:
Use this function
You can call this function just after adding new divs.
If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:
我把它变成了一个 jQuery 函数:
所以你有一个像“#boo”这样的大 div 和里面所有的小 div:
由于 Chrome 中的错误,您需要“? 1 : -1”,没有这个,它不会对超过 10 个 div 进行排序! http://blog.rodneyrehm.de/archives/14 -Sorting-Were-Doing-It-Wrong.html
I made this into a jQuery function:
So you have a big div like "#boo" and all your little divs inside of there:
You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html
在这里回答了同样的问题:
重新发布:
经过许多搜索后我决定有关如何在 jquery 中排序的博客。总之,按数据属性对jquery“类数组”对象进行排序的步骤...
Html
普通 jquery 选择器
让我们按数据顺序对其进行排序
了解 getSorted() 的工作原理。
希望这会有所帮助!
Answered the same question here:
To repost:
After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...
Html
Plain jquery selector
Lets sort this by data-order
See how getSorted() works.
Hope this helps!
我用它来对图像库进行排序,其中排序数组将通过 ajax 调用进行更改。希望它对某人有用。
小提琴:http://jsfiddle.net/ruys9ksg/
I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.
Fiddle: http://jsfiddle.net/ruys9ksg/