gpt4 book ai didi

javascript - jQuery 按首字母分组

转载 作者:行者123 更新时间:2023-11-30 12:08:40 24 4
gpt4 key购买 nike

我在 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>

关于javascript - jQuery 按首字母分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com