2014-10-02 87 views
3

如何更改每個元素,但保留最後一個元素的方式?通過除最後一個元素之外的所有元素循環

jQuery(".diaryevent .field-name-field-category .field-items .field-item a") 
.each(function(e) 
{ 
    var text = jQuery(this).text(); 
    jQuery(this).html(text + ','); 
}); 

我需要在哪裏添加例如not(":last-child"):not(:last-child)

+0

'的jQuery( 「diaryevent點域名稱字段類別點域項點域項目一:沒有(:最後一個孩子)」){.... }' – 2014-10-02 07:46:53

+0

其中是html – 2014-10-02 07:49:04

+0

http://jsfiddle.net/vuwzo4bo/在這裏(我需要在除最後一個字段的每個字段上添加逗號) – josaric 2014-10-02 07:56:01

回答

6

無需循環使用每個。使用正確的選擇器,您可以選擇除最後一個之外的所有元素。

jQuery(".field-name-field-category > .field-items > .field-item:not(:last) > a") 
 
.text(function(_, text) { 
 
    return text + ','; 
 
});
/* Just to see the commas better :) */ 
 
a { text-decoration:none;color:#333; }
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<div class="field field-name-field-category field-type-taxonomy-term-reference field-label-hidden"> 
 
    <div class="field-items"> 
 
    <div class="field-item even"><a href="/category/business" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Business</a> 
 
    </div> 
 
    <div class="field-item odd"><a href="/category/code" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Code</a> 
 
    </div> 
 
    <div class="field-item even"><a href="/category/training" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Training</a> 
 
    </div> 
 
    </div> 
 
</div>

+0

是的,這是正確和優雅的方式 – 2014-10-02 08:09:55

+0

非常感謝! – josaric 2014-10-02 08:20:42

0

根據API,jQuery的每個函數的第一個參數是數組的索引..

你可以用數組的長度進行比較,以達到你想要什麼

var arr = jQuery(".diaryevent .field-name-field-category .field-items .field-item a"); 

arr.each(function(e) 
{ 
    if(e === arr.length-1) { 
     return; 
    } 
    var text = jQuery(this).text(); 
    jQuery(this).html(text + ','); 
}); 

小提琴: jsfiddle.net/Lgwtcdzs/1

+0

不工作...您可以在這裏嘗試您的代碼嗎? jsfiddle.net/vuwzo4bo – josaric 2014-10-02 07:56:38

+0

不工作,因爲jQuery沒有在小提琴中定義,你的選擇器最後還是錯過了'''看看這裏http://jsfiddle.net/Lgwtcdzs/1/(抱歉忘了保存改變小提琴第一次) – montexristos 2014-10-02 08:01:27

+0

你給我發了同樣的東西... – josaric 2014-10-02 08:06:51

相關問題