2010-03-20 7 views
1

(루프 클래스를 통해) 가정 내 코드는 다음과 같다 :JQuery는 어떻게 사용합니까?

<td class="apple"> 
<div class="worm"> 
text1 
</div> 
</td> 

<td class="apple"> 
<div class="worm"> 
text2 
</div> 
</td> 

<td class="apple"> 
<div class="worm"> 
text3 
</div> 
</td> 

어떻게 "TD 클래스 사과"와 모든 것을 통해 내가 루프, 다음 ID가 "벌레"와 내부 사업부의 텍스트를 잡아, .attr() 각각을 해당 텍스트로 설정 하시겠습니까?

결과 :

<td class="apple" title="text1"> 
<div class="worm"> 
text1 
</div> 
</td> 

<td class="apple" title="text2" > 
<div class="worm"> 
text2 
</div> 
</td> 

<td class="apple" title="text3"> 
<div class="worm"> 
text3 
</div> 
</td> 

당신

답변

6
$('td.apple').each(function() { 
    $(this).attr('title', $('div.worm', this).text()); 
}); 

또는 (jQuery를 1.4로 지원)이 짧은 버전 감사합니다 :

$('td.apple').attr('title', function() { 
    return $('div.worm', this).text(); 
});​ 
+0

하지만 $ ("div.worm") ... Jquery는 그 클래스의 웜이라는 것을 알고 있습니까? – TIMEX

+0

나는'tr.apple' 대신에'td.apple'을 쓰고 있다고 확신합니다. –

+0

@Jeroen : 예, 오타입니다. 감사. –

1

이 트릭을 할해야합니다.

//We will iterate through each td which has class of apple. 
$('td.apple').each(
    function() 
    { 
     //'this' in the function refers to the current td. 
     //we will try to find a div with class 'worm' inside this td. 
     var title = $(this).find('div.worm').text(); 
     $(this).attr('title', title); 
    } 
); 
0

나는 당신이 당신의 학교 숙제를하기 위해 나를 사용하는 경우 당신은 내가 꿀벌의 전체 전화 부스에서 당신을 잠급니다 td class="apple"

$("td.apple").each(function(){ 
    this.title=$(this).find("div").text(); 
}); 

을 의미 가정합니다.

+0

코드가 크로스 브라우저에서 작동하도록 'attr'메서드를 사용하는 것을 선호합니다. – SolutionYogi

+0

@SolutionYogi :이 구조 ('this.title')에서 작동하지 않는 브라우저 (jQuery가 작동하는 브라우저)를 알고 있습니까? 의심 스럽다. –

+0

마르코, 나는 고쳐 쓴다. 스펙 (http://www.w3.org/TR/html401/struct/global.html#h-7.4.3)을 살펴보면 'title'속성이 모든 요소에서 유효하다는 것을 알았습니다. 웬일인지, 나는 그것이 어떤 요소에 대해서만 유효하다는 인상 아래에 있었다. – SolutionYogi

2

올바른 응답에 추가하려면 찾기보다는 어린이를 사용하는 것이 좋습니다. 아이들은 재귀 적이 아니며 최적화에 도움이됩니다. TD를 통해 재귀가 필요한 경우가 아니면

$("td.apple").each(function() { 
    $(this).attr('title', $(this).children("div.worm").text()); 
}); 
+1

의미가 있습니다. '웜'클래스를 'div'선택자에 추가하는 것을 잊었습니다. – SolutionYogi

+0

미안, 또한 title이 아닌 attr을 사용하도록 변경되었습니다. –

관련 문제