2015-12-25 31 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'),然後附加容器。 –