2012-09-24 59 views
2

我甚至不確定這是否可能,但讓我們走了。jQuery:爲元素添加標題屬性並從以下元素插入文本

我有這樣的HTML動態地爲每個圖像生成:

<a href="image.jpg" class="thickbox"> 
    <img src="thumb.jpg" title="This is the title" alt="" /> 
</a> 

不知怎的,我需要從thumb.jpg title屬性並將其複製到周圍的錨,這將使這個結果:

<a href="image.jpg" class="thickbox" title="This is the title" alt=""> 
    <img src="thumb.jpg" title="This is the title" alt="" /> 
</a> 

如果可以用jQuery來實現,我會很高興。

在此先感謝。

回答

3

可以傳遞到attr()(或prop())函數和寫類似:

$("a.thickbox").attr("title", function() { 
    return $(this).find("img").attr("title"); 
}); 

(我用attr()在上面的代碼中強調,我們要創建的是HTML屬性的事實prop(),這創建或更新DOM屬性,會給出相同的結果)。

4
$('a.thickbox img').each(function(key,$elem){ 
    $(this).parent().attr('title',$(this).attr('title')); 
}); 

循環使用每一個,如果你有多個圖像。否則使用該函數中的行並用$('a.thickbox img')替換$(this)

+0

工作完美。快速響應的榮譽! – Miker

+1

不要忘記接受答案。 – Barmar

0

遍歷使用.each()而且,對於那些與父母<a>縮略圖,設置父稱號的IMG的稱號。

$("img[src='thumb.jpg']").each(function() { 
    $(this).parent('a.thickbox').attr('title', this.title); 
});