Javascript 如何使用JQuery来实现这一点?(在类中循环)
假设我的代码如下:Javascript 如何使用JQuery来实现这一点?(在类中循环),javascript,jquery,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">
<div class="worm">
text1
</div>
</td>
<td class="apple">
<div class="worm">
text2
</div>
</td>
<td class="apple">
<div class="worm">
text3
</div>
</td>
文本1
文本2
文本3
如何使用“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>
文本1
文本2
文本3
多谢各位
$('td.apple').each(function () {
$(this).attr('title', $('div.worm', this).text());
});
或此较短版本(从jQuery 1.4开始支持):
或此较短版本(从jQuery 1.4开始支持):
这应该能奏效
//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);
}
);
这应该能奏效
//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);
}
);
我猜你的意思是
td class=“apple”
如果你利用我做你的学校作业,我会把你锁在一个装满蜜蜂的电话亭里。我猜你的意思是
td class=“apple”
如果你利用我做你的学校作业,我会把你锁在一个装满蜜蜂的电话亭里。为了补充正确的回答,我建议使用儿童而不是寻找。子对象不是递归的,任何一点优化都有帮助。除非你需要通过TD的递归
$("td.apple").each(function() {
$(this).attr('title', $(this).children("div.worm").text());
});
为了增加正确的回答,我建议使用children而不是find。子对象不是递归的,任何一点优化都有帮助。除非你需要通过TD的递归
$("td.apple").each(function() {
$(this).attr('title', $(this).children("div.worm").text());
});
但是$(“div.worm”)…Jquery会知道这是那个类的蠕虫吗?我很确定你的意思是
td.apple
,而不是tr.apple
-1。您的attr行将拉入所有div.worm,无论它是否是td的子项。@alex:说得好。修复(添加了上下文)。对不起,我太累了@对不起,我伤害了你的感情。我希望我最终帮助了亚历克斯。感觉如何?你在开玩笑吧?无论如何,在你修正了你的答案后,我删除了我的否决票。但是$(“div.worm”)…Jquery会知道这是那个类的蠕虫吗?我很确定你的意思是td.apple
,而不是tr.apple
-1。您的attr行将拉入所有div.worm,无论它是否是td的子项。@alex:说得好。修复(添加了上下文)。对不起,我太累了@对不起,我伤害了你的感情。我希望我最终帮助了亚历克斯。感觉如何?你在开玩笑吧?无论如何,在您修复您的答案后,我删除了我的否决票。我更希望使用“attr”方法来确保代码可以跨浏览器工作。@SolutionYogi:您知道有哪个浏览器(jQuery使用的浏览器)不能使用此构造(this.title
)?我对此表示怀疑。马可,我可以接受更正。我查看了spec(),发现“title”属性对所有元素都有效。出于某种原因,我觉得它只对某些元素有效。我更喜欢使用“attr”方法来确保代码可以跨浏览器工作。@SolutionYogi:您知道有哪个浏览器(jQuery在其中工作)不能使用此构造(this.title
)吗?我对此表示怀疑。马可,我可以接受更正。我查看了spec(),发现“title”属性对所有元素都有效。出于某种原因,我觉得它只对某些元素有效。有道理。您忘记将“worm”类添加到“div”选择器中。很抱歉,更改了,也使用了attr而不是title。这很有意义。您忘了将“worm”类添加到“div”选择器中。很抱歉,已更改,同时使用attr而不是title。