2011-04-09 81 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>"; 
});