假设我的代码如下:
<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>谢谢
发布于 2010-03-20 08:09:10
$('td.apple').each(function () {
$(this).attr('title', $('div.worm', this).text());
});或此较短的版本(从jQuery 1.4开始支持):
$('td.apple').attr('title', function () {
return $('div.worm', this).text();
});发布于 2010-03-20 08:22:12
为了添加正确的响应,我建议使用子代而不是find。子对象不是递归的,任何一点优化都会有所帮助。除非你需要通过TD进行递归。
$("td.apple").each(function() {
$(this).attr('title', $(this).children("div.worm").text());
});发布于 2010-03-20 08:14:30
这应该能起到作用。
//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);
}
);https://stackoverflow.com/questions/2481283
复制相似问题