JavaScript - 对 SELECT 选项进行排序

发布于 2024-09-07 13:16:36 字数 797 浏览 4 评论 0原文

我使用 PHP 扫描目录并列出所有 .xml 文件。每个 XML 文件都包含“名称”元素和“日期”元素。每个 XML 文件的“name”元素作为选项列在选择列表中。这工作得很好,但是,每个 XML 文件中的“日期”元素都不同,并且包含如下日期格式:mm/dd/yyyy。我想要弄清楚如何做是根据日期对项目进行排序,最早的日期是列表中的第一个,最新的日期在最后。

现在假设每个项目的“日期”元素都有不同的值。我需要对这些项目进行排序,最早日期在前。我不确定如何将“日期”元素数据存储在某处,以便 JavaScript 可以处理它。如果这是一个非常模糊的描述,我很抱歉,它已经让我困惑了一段时间,尝试解释起来也很混乱。

更新

所以现在这就是我正在做的事情:

<select name="sel_id" onchange="this.form.submit()" size="20">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
<option value="item4">Item 4</option>
</select>

我想最有帮助的一件事是知道除了 value 属性之外是否还有一种方法可以将日期存储在标签中的某个位置,看看它是如何使用的。日期本身不是问题,我已经想通了,这只是将其存储在某个地方以便可以称为客户端的问题。

Using PHP, I scan a directory and list all of the .xml files. Each XML file contains both a "name" element and a "date" element. The "name" element for each XML file is listed as an option in the select list. This works perfectly fine, however, the "date" element in each XML file is different and contains a date format like this: mm/dd/yyyy. What I am trying to figure out how to do is sort the items according to the date, with the earliest date being first one the list and the most recent at the end.

Now say each of those items has a different value for the "date" element. I need to sort those items with the earliest date being first. I'm not sure how I can store the "date" element data somewhere so that it can be handled by JavaScript. I'm sorry if this is a very vague description, it's been baffling me for a while and it's a been confusing to try and explain.

UPDATED

So right now this is what I have working:

<select name="sel_id" onchange="this.form.submit()" size="20">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
<option value="item4">Item 4</option>
</select>

I guess one thing that would majorly help is knowing if there's a way to store the date somewhere in the tags besides the value attribute seeing how it's already being used. The date itself isn't a concern, I have that much figured it, it's just a matter of storing it somewhere so that it can be called client side.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦年海沫深 2024-09-14 13:16:36

已更新

您需要:

  • 对日期使用自定义属性
  • 使用 sort() 函数的自定义比较函数参数
  • 转换为数组以进行排序
  • 转换日期以进行字符串比较 (mm/dd/yyyy -> yyyy-mm-dd)

查看实际效果

[测试于: IE 5.5+、FF 2+、Chrome 4+、Safari 4+、Opera 9.6+]

HTML:

<select name="sel_id" id="sel_id" size="4">
  <option value="item2" date="02-01-2009">Item 2</option>
  <option value="item3" date="01-05-2010">Item 3</option>
  <option value="item1" date="10-06-2007">Item 1</option>
  <option value="item4" date="04-05-2011">Item 4</option>
</select>

Javascript:

// array functions are not working
// on nodeLists on IE, we need to
// to convert them to array
function toArray( obj ) {
  var i, arr = [];
  for ( i = obj.length; i--; ){
    arr[i] = obj[i];
  }
  return arr;
}

// custom compare function for sorting
// by the hidden date element
function sortByDate( el1, el2 ) {
  var a = convertToDate( el1.getAttribute("date") ),
      b = convertToDate( el2.getAttribute("date") );
  if ( a < b ) return -1;
  else if( a > b ) return 1;
  else return 0;
}

// convert date for string comparison
function convertToDate( date ) {
  date = date.split("-");
  return date[2] + "-" + date[0] + "-" + date[1];
}

// select the elements to be ordered
var itemsId = document.getElementById("sel_id"),
    items   = itemsId.getElementsByTagName("option"),
    len     = items.length;

// convert to array, to make sorting possible
items = toArray( items );

// do the item sorting by their date
items = items.sort( sortByDate );

// append them back to the parent in order
for ( var i = 0; i < len; i++ ) {
  itemsId.appendChild( items[i] );
}

Updated

You need to:

  • use a custom attribute for the dates
  • use sort() function's custom compare function parameter
  • convert to array to make sorting possible
  • convert the dates for string comparison (mm/dd/yyyy -> yyyy-mm-dd)

See it in action

[Tested on: IE 5.5+, FF 2+, Chrome 4+, Safari 4+, Opera 9.6+]

HTML:

<select name="sel_id" id="sel_id" size="4">
  <option value="item2" date="02-01-2009">Item 2</option>
  <option value="item3" date="01-05-2010">Item 3</option>
  <option value="item1" date="10-06-2007">Item 1</option>
  <option value="item4" date="04-05-2011">Item 4</option>
</select>

Javascript:

// array functions are not working
// on nodeLists on IE, we need to
// to convert them to array
function toArray( obj ) {
  var i, arr = [];
  for ( i = obj.length; i--; ){
    arr[i] = obj[i];
  }
  return arr;
}

// custom compare function for sorting
// by the hidden date element
function sortByDate( el1, el2 ) {
  var a = convertToDate( el1.getAttribute("date") ),
      b = convertToDate( el2.getAttribute("date") );
  if ( a < b ) return -1;
  else if( a > b ) return 1;
  else return 0;
}

// convert date for string comparison
function convertToDate( date ) {
  date = date.split("-");
  return date[2] + "-" + date[0] + "-" + date[1];
}

// select the elements to be ordered
var itemsId = document.getElementById("sel_id"),
    items   = itemsId.getElementsByTagName("option"),
    len     = items.length;

// convert to array, to make sorting possible
items = toArray( items );

// do the item sorting by their date
items = items.sort( sortByDate );

// append them back to the parent in order
for ( var i = 0; i < len; i++ ) {
  itemsId.appendChild( items[i] );
}


绮筵 2024-09-14 13:16:36

简短而甜蜜。此版本还根据 OP 的要求采用 mm-dd-yyyy 格式的日期。

<form>
  <select id="myList">
    <option value="07-01-2010">Item 2</option>
    <option value="09-21-2009">Item 1</option>
    <option value="08-22-2010">Item 3</option>
  </select>
</form>
<script>
  var list    = document.forms[0].myList,
      opts    = list.options,
      len     = opts.length,
      sorted  = [].slice.call(opts).sort(function(a,b){
        return fixDate(a.value) < fixDate(b.value) ? -1 : 1;
      });

  for (var i=0; i<len; i++) {
    list.appendChild(sorted[i]);
  }

  // convert m-d-y to y-m-d
  function fixDate (d) {
    var a=d.split('-');
    a.unshift(a.pop()); 
    return a.join('-');
  }

</script>

Short and sweet. This version also accounts for dates being in mm-dd-yyyy format as per the OP's request.

<form>
  <select id="myList">
    <option value="07-01-2010">Item 2</option>
    <option value="09-21-2009">Item 1</option>
    <option value="08-22-2010">Item 3</option>
  </select>
</form>
<script>
  var list    = document.forms[0].myList,
      opts    = list.options,
      len     = opts.length,
      sorted  = [].slice.call(opts).sort(function(a,b){
        return fixDate(a.value) < fixDate(b.value) ? -1 : 1;
      });

  for (var i=0; i<len; i++) {
    list.appendChild(sorted[i]);
  }

  // convert m-d-y to y-m-d
  function fixDate (d) {
    var a=d.split('-');
    a.unshift(a.pop()); 
    return a.join('-');
  }

</script>
草莓味的萝莉 2024-09-14 13:16:36

我将从上面的 galambalazs 中获取答案,但使用数据属性而不是日期属性。因为“数据日期”被认为是符合标准的,而“日期”只是一个自定义属性。

I would take the answer from galambalazs above but use the data attribute instead of a date attribute. as "data-date" is considered standards compliant while "date" is just a custom attribute.

伴随着你 2024-09-14 13:16:36

您可以将日期表示为选项值,或使用 数据属性 来存储它们有一个选项。

<option value="2010-07-05">..</option>

<option data-date="2010-07-05">..</option>

假设您的选择列表如下所示:

<select id="myList">
    <option value="2010-07-01">Item 1</option>
    <option value="2010-06-21">Item 1</option>
    <option value="2010-08-22">Item 1</option>
    ..
</select>

使用内置的 Array.sort< /a> 函数使用自定义比较器对节点进行排序,排序后将它们重新插入到选择列表中。 在此处查看示例

/**
 * Sorts option elements by value attribute which holds a date
 *
 * @param {HTMLOptionElement} a first option
 * @param {HTMLOptionElement} b second option
 *
 * @returns {Integer}
 */
var sortByDate = function(a, b) {
    return new Date(a.value) - new Date(b.value);
}

var list = document.getElementById("myList");
var options = list.getElementsByTagName("option");
// NodeList that we get in previous step is an array-like
// object but not actually an array. Some call it a fuck-up,
// but regardless we need to convert it to an array.
var optionsArray = Array.prototype.slice.call(options);

// Now that we have an array, we can use the sort method (in-place sorting)
optionsArray.sort(sortByDate);

// re-insert the sorted nodes
for(var i = 0; i < optionsArray.length; i++) {
    list.appendChild(optionsArray[i]);
}
​

You can represent the dates as option values, or use a data attribute to store them with an option.

<option value="2010-07-05">..</option>

or

<option data-date="2010-07-05">..</option>

Assuming your select list looks like this:

<select id="myList">
    <option value="2010-07-01">Item 1</option>
    <option value="2010-06-21">Item 1</option>
    <option value="2010-08-22">Item 1</option>
    ..
</select>

Use the inbuilt Array.sort function with a custom comparator to sort the nodes, and once sorted re-insert them into the select list. See an example here.

/**
 * Sorts option elements by value attribute which holds a date
 *
 * @param {HTMLOptionElement} a first option
 * @param {HTMLOptionElement} b second option
 *
 * @returns {Integer}
 */
var sortByDate = function(a, b) {
    return new Date(a.value) - new Date(b.value);
}

var list = document.getElementById("myList");
var options = list.getElementsByTagName("option");
// NodeList that we get in previous step is an array-like
// object but not actually an array. Some call it a fuck-up,
// but regardless we need to convert it to an array.
var optionsArray = Array.prototype.slice.call(options);

// Now that we have an array, we can use the sort method (in-place sorting)
optionsArray.sort(sortByDate);

// re-insert the sorted nodes
for(var i = 0; i < optionsArray.length; i++) {
    list.appendChild(optionsArray[i]);
}
​
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文