jQuery按首字母分组

编程入门 行业动态 更新时间:2024-10-27 21:15:03
本文介绍了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: codepen.io/ponciusz/pen/EPgQKP

How i can do it using jQuery? here i have simple codepen: 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="ajax.googleapis/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按首字母分组

本文发布于:2023-10-23 19:34:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:首字母   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!