遍历除最后一个元素之外的所有元素

jos*_*ric 3 jquery

如何更改每个元素,但最后一个元素保持原样?

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

我需要添加eg not(":last-child"):not(:last-child)

Spo*_*key 6

无需循环使用每个.使用右选择器,您可以选择除最后一个之外的所有元素.

jQuery(".field-name-field-category > .field-items > .field-item:not(:last) > a")
.text(function(_, text) {
  return text + ',';
});
Run Code Online (Sandbox Code Playgroud)
/* Just to see the commas better :) */
a { text-decoration:none;color:#333; }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)