jQuery按首字母分组

jQuery Grouping by first letter

本文关键字:jQuery      更新时间:2023-09-26

我在Wordpress中有一个帖子列表,它看起来像这样:

<div class="products uk-grid uk-grid-width-medium-1-4">
    <a href="#custom-url"><h3>AShape(14)</h3></a>
    <a href="#custom-url"><h3>AShape(20)</h3></a>
    <a href="#custom-url"><h3>CShape(38)</h3></a>
    <a href="#custom-url"><h3>FShape(1)</h3></a>
    <a href="#custom-url"><h3>FShape(4)</h3></a>
    <a href="#custom-url"><h3>ZShape(2)</h3></a> 
    <a href="#custom-url"><h3>ZShape(24)</h3></a> 
</div>

我需要找到一些方法,通过脚本传递所有链接,并在字母组中转换它。所以它应该从链接的所有<h3>中提取第一个字母,并使组像这样:

<div class="products uk-grid uk-grid-width-medium-1-4">
  <div>
    <span>A</span>
    <a href="#custom-url"><h3>AShape(14)</h3></a>
    <a href="#custom-url"><h3>AShape(20)</h3></a>
  </div>
  <div>
    <span>C</span>
    <a href="#custom-url"><h3>CShape(38)</h3></a>
  </div>
  <div>
    <span>F</span>
    <a href="#custom-url"><h3>FShape(1)</h3></a>
    <a href="#custom-url"><h3>FShape(4)</h3></a>
  </div>
  <div>
    <span>Z</span>
    <a href="#custom-url"><h3>ZShape(2)</h3></a> 
    <a href="#custom-url"><h3>ZShape(24)</h3></a> 
  </div>
</div>

如何使用jQuery?这里我有一个简单的代码笔:http://codepen.io/ponciusz/pen/EPgQKP

您可以迭代每个子元素,并为每个字母创建相应的容器。在下面的示例中,如果一个div容器还不存在,则该容器将附加一个自定义的data-letter属性。

正如我在评论中提到的,我还建议将a元素也放在h3元素中:

$('.products > h3').each(function () {
  var letter = $('a', this).text().charAt(0);
  
  if (!$(this).parent().find('[data-letter="'+ letter +'"]').length) {
    $(this).parent().append('<div data-letter="'+ letter+'"><span>'+ letter +'</span></div>');
  }
  $(this).parent().find('[data-letter="'+ letter +'"]').append(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="products uk-grid uk-grid-width-medium-1-4">
    <h3><a href="#custom-url">AShape(14)</a></h3>
    <h3><a href="#custom-url">AShape(20)</a></h3>
    <h3><a href="#custom-url">CShape(38)</a></h3>
    <h3><a href="#custom-url">FShape(1)</a></h3>
    <h3><a href="#custom-url">FShape(4)</a></h3>
    <h3><a href="#custom-url">ZShape(2)</a></h3> 
    <h3><a href="#custom-url">ZShape(24)</a></h3> 
</div>