如何使用 JavaScript 根据日期对元素进行排序

how to sort element based on a date with javascript

本文关键字:元素 排序 日期 何使用 JavaScript      更新时间:2023-09-26

我正在使用Filterizr作为模板来显示我们的出版物。我插入了出版年份和作者。当尝试根据出版年份或作者(按字母顺序)进行排序时,我看到图像在移动,但随后我没有得到正确的顺序。你们中的任何一个人可以帮我解决这个排序问题吗?

https://jsfiddle.net/gdhia/yLdtmeqL/

在他们的页面中,他们说了一些我不明白的话:

.filterizr('sort' [,attr] [,sortOrder])

根据某个属性属性按升序或降序对元素进行排序,并在屏幕上重新排列它们。

attr (typeof: String / Default: 'domIndex')
The attribute based on which the elements are sorted. If not provided it defaults to value 'domIndex' and the elements are sorted based on their initial position in the DOM. If its value is set to 'sortData', the elements are sorted based on the value of the user-defined data-sort attribute. Other possible values includes 'w' or 'h' if you wish to sort your elements by width or height (used for layouts of items of different size).

我是Filterizr的作者,您是否正在使用预设的过滤控件?

如果要按作者姓名

对项目进行排序,则需要在每个元素的数据排序属性中的每个项目上都包含该作者姓名。例如

<div class="filtr-item" data-sort="Author name"></div>

然后,排序控件将为您完成其余工作。

如果你想调用公共方法,那么你只需做

//to instantiate your filterizr
var fltr = $('.filtr-container').filterizr(); 
//then to sort, since sortData will be now referring to authors' names
fltr.filterizr('sort', 'sortData', 'asc');

更新:由于显然您想按多个条件进行排序,因此我在 Filterizr 中添加了按自定义用户定义的数据属性进行排序的功能。确保从 GitHub 存储库中获取最新的 Filterizr 版本并尝试以下操作:

<div class="filtr-item" data-author="Author Name" data-publishyear="1990"></div>

然后致电:

fltr.filterizr('sort', 'author', 'asc') //to sort by author name
fltr.filterizr('sort', 'publishyear', 'asc') //to sort by publish year

要为自定义数据属性添加控件,只需添加到选择输入:

<option value="author">Author Name</option>
<option value="publishyear">Publish Year</option>

您可以根据需要添加任意数量的数据属性进行排序,只需记住在将它们的名称作为参数传递时不要包含"data-"部分。我还在 Filterizr 网站上添加了一个深入的排序教程。享受!