我想将image 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);
});
我的代码中有什么错误/缺失?
答案 0 :(得分:2)
你应该得到当前div的子代img
(迭代时):
var att = $(this).find('img').attr('alt');
您正在进行的操作(即重复选择器),您最终会检索多个值,并且只考虑第一个值。所以,每个div都会得到它的类:“John”。
答案 1 :(得分:1)
$('div.field-group_our_people div[class^=".field-items"] img').each(function()
{
var att = $(this).attr('alt');
$(this).parent().addClass(att);
});
答案 2 :(得分:1)
$('.field-group-our-people .field-items img').each(function() {
$(this).parent().addClass( $(this).attr('alt') );
});