0

我只是想写一些代码,对于特定类的每个元素,我需要找到某个属性,然后替换一个元素。我现在拥有的代码如下所示:

<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>"
});

我知道这是不对的,而且它不起作用,但我想不出如何写这个,任何帮助将不胜感激!

编辑

我应该提到元素的数量不是预先确定的。

4

2 回答 2

2

我想你想要以下:

$('.a-photo').each()(function(){
    $(this).css({'background':'url('+$(this).attr('alt') + ') center no-repeat'});
});
于 2011-04-09T06:58:19.830 回答
1

您正在使用each().replaceWithwhich 是一个错误,也是多余的,因为replaceWith已经这样做了。尝试:

$('.a-photo').replaceWith(function(){
  var alt = $(this).attr('alt');
  return "<div class='a-photo' style='background:url("+ alt +") center no-repeat;></div>";
});
于 2011-04-09T06:58:56.047 回答