2011-04-09 3 views
0

나는 특정 클래스의 각 요소에 대해 특정 속성을 찾은 다음 요소를 바꿀 필요가있는 코드를 작성하려고합니다. 내가 가지고있는 코드는 현재 다음과 같습니다.each.replaceWith() 도움말과 함께.

<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' -'해시 '를 의미하지 않습니까? – Cameron

+0

와우, 예, 그게 문제가되지 않습니다. 오타가 오타입니다. – mcbeav

답변

2

나는 당신이 다음 원하는 생각 : 당신은 오류와 replaceWith 이미 같은 작업을 수행 becaue도 불필요 each().replaceWith을 사용하는

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

"url"에는 괄호가 필요합니다. – lukiffer

+0

hahah 그래, 나는 대답을 얻기 전에 바로 그 일을했다. 도와 줘서 고마워! – mcbeav

+0

예, 깜박했습니다. – gor

1

. 시도해보십시오 :

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