按名为“数据字母”的每个属性按字母顺序排序

sort alphatically by each attribute named "data-letter"

本文关键字:排序 顺序 属性 数据字母 数据      更新时间:2023-09-26

我想根据选择框中所选选项的值按字母顺序对具有"数据字母"属性的div进行排序。例如,如果用户在选择框中选择"A",那么每个具有"数据字母"属性的div将按字母顺序排列,例如"A,B,C,D,E等"基于相应的"数据字母"属性内容。任何想法,帮助,线索,建议和建议将不胜感激。谢谢!

网页结构

<div class="select_holder">
    <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
</div>
<div class="box_container">
    <div data-letter="B">
        this is the content of box
    </div>
    <div data-letter="A">
        this is the content of box
    </div>
    <div data-letter="C">
        this is the content of box
    </div>
    <div data-letter="C">
        this is the content of box
    </div>
    <div data-letter="A">
        this is the content of box
    </div>
    <div data-letter="A">
        this is the content of box
    </div>
    <div data-letter="C">
        this is the content of box
    </div>
</div>

我的脚本

$(document).ready(function(){
    $("select").change(function(){
        //$(this).val();
        //I dont know how to make it like sort it up alphatically :(
    });
});

$(document).ready(function(){
    $("select").change(function(){
        var value = this.options[this.selectedIndex].value;
        var box = $('.box_container');
        box.find('div').sort(function(a,b){
          
          if(a.getAttribute('data-letter') == value){
            return 0;
          }
          if( b.getAttribute('data-letter') == value){
            return 1;
          }
          return (a.getAttribute('data-letter') > b.getAttribute('data-letter')?1:-1);
        }).appendTo(box);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select_holder">
    <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
</div>
<div class="box_container">
    <div data-letter="B">
        this is the content of box B
    </div>
    <div data-letter="A">
        this is the content of box A
    </div>
    <div data-letter="C">
        this is the content of box C
    </div>
    <div data-letter="C">
        this is the content of box C
    </div>
    <div data-letter="A">
        this is the content of box A
    </div>
    <div data-letter="Z">
        this is the content of box Z
    </div>
    <div data-letter="A">
        this is the content of box A
    </div>
    <div data-letter="C">
        this is the content of box C
    </div>
      <div data-letter="B">
        this is the content of box B
    </div>
</div>