2011-04-09 44 views
0

我只是想編寫一些代碼,對於特定類的每個元素,我需要找到某個屬性,然後替換一個元素。在代碼中,我現在看起來是這樣的:幫助與.each.replaceWith()jQuery

<div class="a-photo" alt="*/THE IMG SRC*/"></div> 
<div class="a-photo" alt="*/THE IMG SRC*/"></div> 
<div class="a-photo" alt="*/THE IMG SRC*/"></div> 
<div class="a-photo" alt="*/THE IMG SRC*/"></div> 

$('.a-photo').each().replaceWith(function(){ 
var hash = $(this).attr('alt') 
"<div class='a-photo' style='background:url("+ hash +") center no-repeat;></div>" 
}); 

我知道這是不對的,它不工作,但我想不出該怎麼寫,任何幫助將不勝感激!

EDIT

我應該指出,元素的量不是預定的。

+0

你在插入一個不存在的變量'alt' - 你確定你不是指'hash'嗎? – Cameron 2011-04-09 06:53:03

+0

哎呦,是啊讓我解決這個問題,這不是問題,只是一個錯字。 – mcbeav 2011-04-09 06:55:19

回答

2

我想你想要以下:

$('.a-photo').each()(function(){ 
    $(this).css({'background':'url('+$(this).attr('alt') + ') center no-repeat'}); 
}); 
+1

「url」需要括號。 – lukiffer 2011-04-09 06:59:51

+0

哈哈耶,我剛纔那樣做,就在我得到答案之前,謝謝一幫幫忙! – mcbeav 2011-04-09 07:04:46

+0

是的,我忘記了 – gor 2011-04-09 07:14:44

1

您正在使用each().replaceWith這是一個錯誤,也多餘becaue replaceWith已經做了同樣的。試試:

$('.a-photo').replaceWith(function(){ 
    var alt = $(this).attr('alt'); 
    return "<div class='a-photo' style='background:url("+ alt +") center no-repeat;></div>"; 
});