2012-10-22 49 views
1

查看其他一些帖子,找到我需要的代碼,但並不完全符合我需要的代碼。根據圖像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。我怎樣才能做到這一點?

+4

'ID'應該是唯一的。你不應該只是爲了解知識'this.alt'複製這樣的 –

回答

3

ID應該是唯一的..你不應該重複這樣的ID。嘗試將其更改爲類class="img-wrap"並查看下面的代碼。

HTML:

<div class="img-wrap"> 
    <div class="img-icon"> 
     <a href=""> 
     <img alt="home" /> 
     </a> 
    </div> 
</div> 

代碼:

$('img').each(function() { 
    $(this).closest('.img-wrap').addClass(this.alt); 
}); 
+0

+1 ID:d –

+0

完美工作。謝謝! – jfrosty

1
$('img').each(function() { 
$(this).parents('#img-wrap').addClass($(this).attr('alt')); 
}); 

OR

$('img').each(function() { 
    $(this).parent().parent().parent().addClass($(this).attr('alt')); 
    }); 
//to make it more obvious why it is not selecting the #img-wrap <div> 

是的,#IDs只能使用一次,使用一個類來代替,如果這重演

0

嘗試在HTML頁面中使用.closest()

注意標識應該是獨一無二的..嘗試給div一個,而不是一個ID

$('img').each(function() { 
     $(this).closest('.img-wrap').addClass($(this).attr('alt')); 
    }); 


<div class="img-wrap"> 
    <div class="img-icon"> 
    <a href=""> 
     <img alt="home" /> 
    </a> 
    </div>