我如何使用JQuery来做到这一点? (循环课程)

时间:2010-03-20 00:05:59

标签: javascript 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 class apple”遍历所有内容,然后使用id“worm”获取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>

谢谢

4 个答案:

答案 0 :(得分: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();
});​

答案 1 :(得分:2)

要添加正确的回复,我建议使用儿童而不是找到。孩子不是递归的,任何一点优化都有帮助。除非你需要通过TD的递归。

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

答案 2 :(得分: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);
   }
);

答案 3 :(得分:0)

我认为你的意思是td class="apple"

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

如果你用我做你的学校作业,我会把你锁在一个满是蜜蜂的电话亭里。