查看其他一些帖子,找到我需要的代碼,但並不完全符合我需要的代碼。根據圖像alt標籤向父元素添加一個類?
我想添加一個類到基於圖像的alt標籤的父元素。
所以從這個:
<div class="img-wrap">
<div class="img-icon">
<a href="">
<img alt="home" />
</a>
</div>
</div>
要這樣:
<div class="img-wrap home">
<div class="img-icon">
<a href="">
<img alt="home" />
</a>
</div>
</div>
下面是我使用的代碼:
$('img').each(function() {
$(this).parent().addClass($(this).attr('alt'));
});
雖然這增加了所需要的類,它增加了它到「a」......但是我希望它添加到#img-wrap。我怎樣才能做到這一點?
'ID'應該是唯一的。你不應該只是爲了解知識'this.alt'複製這樣的 –