代码之家  ›  专栏  ›  技术社区  ›  user

JavaScript-排序选择选项

  •  3
  • user  · 技术社区  · 14 年前

    现在假设这些项中的每一项对于“date”元素都有不同的值。我需要把那些东西分类,最早的日期是第一个。我不确定如何将“date”元素数据存储在某个地方,以便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属性之外,是否还有一种方法可以将日期存储在标签的某个地方,看看它是如何被使用的。日期本身不是一个问题,我已经计算了很多,它只是一个存储在某个地方,以便它可以被称为客户端的问题。

    4 回复  |  直到 14 年前
        1
  •  7
  •   galambalazs    10 年前

    你需要:

    • 对日期使用自定义属性
    • 使用sort()函数的自定义比较函数参数
    • 转换为数组以使排序成为可能

    See it in action

    [测试对象: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] );
    }
    

        2
  •  2
  •   Dagg Nabbit    14 年前

    又短又甜。根据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>
    
        3
  •  0
  •   Austin_G    12 年前

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

        4
  •  -1
  •   Anurag    14 年前

    data attribute 使用选项存储它们。

    <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 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]);
    }
    ​