通过名为" data-letter"的每个属性进行排序。

时间:2015-06-17 12:06:16

标签: javascript jquery

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

html结构

<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 :(
    });
});

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
$(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);
    });
});
&#13;
<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>
&#13;
&#13;
&#13;