[英]How do I use JQuery to do this? (Loop through the classes)
假設我的代碼是這樣的:
<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>
謝謝
$('td.apple').each(function () {
$(this).attr('title', $('div.worm', this).text());
});
或這個較短的版本(jQuery 1.4開始支持):
$('td.apple').attr('title', function () {
return $('div.worm', this).text();
});
為了增加正確的答案,我建議使用孩子而不是查找。 子級不是遞歸的,優化的任何幫助。 除非您需要通過TD進行遞歸。
$("td.apple").each(function() {
$(this).attr('title', $(this).children("div.worm").text());
});
這應該可以解決問題。
//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.apple").each(function(){
this.title=$(this).find("div").text();
});
如果您要用我來做學校作業,我會將您鎖在裝滿蜜蜂的電話亭中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.