2011-09-16 24 views
1

所有產品都有一個用於標題的H1,我想將該文本用於IMG的替代文本。我編寫的腳本不起作用。有人能幫助我解決問題嗎?單個產品的樣品在下面更多將在單個頁面上。Jquery:從H1添加IMG替代文本

HTML

<li class="prod"> 
<div class="mainpic"> 
     <div class="popup"> 
      <ul class="data"> 
      <li>feature 1</li> 
      </ul> 
     <p>SKU: 4430757</p> 
</div> 

<img src="images/products/4330-12534-9126-333-TQ.jpg" width="220" height="210" 
alt="Some text" /> 
</div> 

<h1>Avia '5571' Women's Running Shoe</h1> 
</li> 

腳本(這是正確的?):提前

var $target = null; 
var $newtext = null; 

$(".prod").each (function() { 

var target = $(this); 

var newtext = target.find("h1").html(); 

target.each (function() { 

$(this).find(img).attr(newtext); 

}); 

    }); 

謝謝!

回答

3
$('li.prod').each(function() { 
    var img = $(this).find('img'); 
    var h1 = $(this).find('h1'); 
    img.attr('alt', h1.text()); 
}); 

或更短:

$('li.prod').each(function() { 
    $(this).find('img').attr('alt', $(this).find('h1').text()); 
}); 
+0

如果你使用一個變量來存儲$(this),這個解決方案將是完美的。 – Niko

+0

非常感謝!完善! – GermanMan

0
var $target = null; 
var $newtext = null; 

$(".prod").each (function() { 
    var target = $(this); 
    var newtext = target.find("h1").html(); 
    target.find(img).attr("alt",newtext); 
}); 

應該這樣做。您已經將目標定義爲當前元素。無需使用.each就可以了。

0
$('li.prod').each(function() { 
    $('img', this).attr('alt', $('h1', this).text()); 
});