我在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
发布于 2015-12-25 23:03:02
您可以迭代每个子元素,并为每个字母创建相应的容器。在下面的示例中,如果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>
https://stackoverflow.com/questions/34467094
复制相似问题