2015-12-25 33 views
1

我在WordPress的职位列表中的这个样子的:jQuery的分组按首字母

<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做呢? 这里我有简单的codepen:http://codepen.io/ponciusz/pen/EPgQKP

+0

随机附带说明,我建议将锚元素放在'h3'元素中.. –

回答

2

你可以迭代每个子元素,并为每个字母创建相应的容器。在下面的示例中,如果容器尚不存在该字母,则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>

+0

我不明白你为什么使用'.length'就像检查'if exists'一样吗? – Ponciusz

+0

@Ponciusz是的,正好。一个jQuery对象与数组类似,所以在这种情况下,我正在检查该元素是否不存在('!$(...)。length'),然后附加容器。 –