Javascript jQuery:在 tr 中选择每个 td
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4996521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: selecting each td in a tr
提问by gh9
I need a way to interact with each td
element in a tr
.
我需要一种方法来与每个互动td
的元素tr
。
To elaborate, I would like to access the first table row, then the first column, then the second column, etc. Then move onto the second row and repeat the process.
详细说明,我想访问表的第一行,然后是第一列,然后是第二列,等等。然后移动到第二行并重复该过程。
Something like this (pseudo-code):
像这样(伪代码):
for each row in table
{
for each column in row
{
do cool things
}
}
jQuery:
jQuery:
$('#tblNewAttendees tr').each(function() {
alert('tr');
//Cool jquery magic that lets me iterate over all the td only in this row
$(magicSelector).each(function(){
alert('hi');
});
});
HTML:
HTML:
<table>
<thead>
<th>someHeader</th>
</thead>
<tbody>
<tr>
<td>want to grab this first</td>
<td> this second </td>
</tr>
<tr>
<td>this third</td>
<td>this fourth</td>
</tr>
</tbody>
</table>
回答by Gregg
You can simply do the following inside your TR loop:
您可以简单地在 TR 循环中执行以下操作:
$(this).find('td').each (function() {
// do your cool stuff
});
回答by user113716
You don't need a jQuery selector at all. You already have a reference to the cells in each row via the cells
property.
您根本不需要 jQuery 选择器。您已经通过cells
属性引用了每行中的单元格。
$('#tblNewAttendees tr').each(function() {
$.each(this.cells, function(){
alert('hi');
});
});
It is far more efficient to utilize a collection that you already have, than to create a new collection via DOM selection.
利用已有的集合比通过 DOM 选择创建新集合要高效得多。
Here I've used the jQuery.each()
(docs)method which is just a generic method for iteration and enumeration.
在这里,我使用了jQuery.each()
(docs)方法,它只是迭代和枚举的通用方法。
回答by Rocket Hazmat
Your $(magicSelector)
could be $('td', this)
. This will grab all td
that are children of this
, which in your case is each tr
. This is the same as doing $(this).find('td')
.
你$(magicSelector)
可能是$('td', this)
。这将抓取所有td
的孩子this
,在你的情况下是每个tr
. 这与做$(this).find('td')
.
$('td', this).each(function() {
// Logic
});
回答by Poul
expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.
扩展 'each' 函数上方的答案将返回 table-cell html 对象。将其包装在 $() 中将允许您对其执行 jquery 操作。
$(this).find('td').each (function( column, td) {
$(td).blah
});