2010-03-20 29 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爲「蟲」的div文字,然後將每個.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 2010-03-20 00:10:33

+0

我很確定你的意思是'td.apple'而不是'tr.apple' – 2010-03-20 00:10:49

+0

@Jeroen:是的,是一個錯字。謝謝。 – 2010-03-20 00:11:52

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 2010-03-20 00:16:08

+0

@SolutionYogi:你知道一個瀏覽器(即jQuery的作品),不會使用這個構造('this.title')嗎?我不信。 – 2010-03-20 00:19:31

+0

Marco,我糾正了。我查看了規範(http://www.w3.org/TR/html401/struct/global.html#h-7.4.3),發現'title'屬性在所有元素上都是有效的。出於某種原因,我的印象是它只對某些元素有效。 – SolutionYogi 2010-03-20 00:28:32

2

要添加到正確的答案,我會建議使用兒童而不是找到。兒童不是遞歸的,任何一點優化都有幫助。除非你需要通過TD的遞歸。

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

有道理。您忘了將'蠕蟲'類添加到您的'div'選擇器。 – SolutionYogi 2010-03-20 00:24:28

+0

對不起,改用attr而不是title。 – 2010-03-20 00:24:30