我在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
答案 0 :(得分:3)
您可以迭代每个子元素并为每个字母创建相应的容器。在下面的示例中,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>