1

我想将图像 alt 属性作为一个类添加到其容器元素中。标记:

<div class="field-group-our-people">
  <div class="field-items even>
   <img alt="John">
  </div>
  <div class="field-items odd>
   <img alt="Kevin">
  </div>
  <div class="field-items even>
   <img alt="Kate">
  </div>
  <div class="field-items odd>
   <img alt="Martin">
  </div>
</div>

变成这样:

<div class="field-group-our-people">
      <div class="field-items even john>
       <img alt="John">
      </div>
      <div class="field-items odd kevin>
       <img alt="Kevin">
      </div>
      <div class="field-items even kate>
       <img alt="Kate">
      </div>
      <div class="field-items odd martin>
       <img alt="Martin">
      </div>
</div>

我的 Jquery 代码(但不工作):

//Add the image alt attribute as class for individual styling
$('.group_our_people .field-item').each(function() {
  var att = $('.group_our_people .field-item img').attr('alt');               
  $(this).addClass(att);        
});

我的代码有什么问题/缺少什么?

4

3 回答 3

2

你应该得到img当前 div 的子元素(在迭代中):

var att = $(this).find('img').attr('alt');

您正在做的方式(即重复选择器),您最终会检索多个值,并且只考虑第一个值。所以,每个 div 都会得到它的类:“John”。

于 2012-04-29T10:50:43.697 回答
1
$('div.field-group_our_people div[class^=".field-items"] img').each(function()
{
  var att = $(this).attr('alt');               
  $(this).parent().addClass(att);        
});
于 2012-04-29T10:51:41.347 回答
1
$('.field-group-our-people .field-items img').each(function() {
     $(this).parent().addClass( $(this).attr('alt') );
});
于 2012-04-29T10:51:58.357 回答