jQuery按首字母分组 [英] jQuery Grouping by first letter

查看:251
本文介绍了jQuery按首字母分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have list of posts in Wordpress its looks like this:

<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>中获取第一个字母,并进行如下分组:

I need to find some way to pass all links through script and transform it in letter groups. So it should take first letter from all <h3> of links and make groups like this:

<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做到这一点? 在这里,我有一个简单的Codepen: http://codepen.io/ponciusz/pen/EPgQKP

How i can do it using jQuery? here i have simple codepen: http://codepen.io/ponciusz/pen/EPgQKP

推荐答案

您可以遍历每个子元素并为每个字母创建相应的容器.在下面的示例中,如果div容器尚不包含该字母的容器,则该容器将附加自定义data-letter属性.

You could iterate over each of the children elements and create corresponding containers for each letter. In the example below, a div container is appending with a custom data-letter attribute if a container does not already exist for that letter.

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

As I mentioned in the comments, I'd also suggest placing the a element inside of the h3 elements as well:

$('.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>

这篇关于jQuery按首字母分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆