Javascript 对于HTML表格列中的每个单元格,是否执行X?
只是想看看有没有更好的方法 假设我有一个标准的HTML表,其中有几行和几列数据。我想做的是对属于该列的每一行或单元格应用一个函数。我现在尝试的是一个3深度的循环,实际上并不是最好的Javascript 对于HTML表格列中的每个单元格,是否执行X?,javascript,jquery,css,html-table,Javascript,Jquery,Css,Html Table,只是想看看有没有更好的方法 假设我有一个标准的HTML表,其中有几行和几列数据。我想做的是对属于该列的每一行或单元格应用一个函数。我现在尝试的是一个3深度的循环,实际上并不是最好的 <table id="myTable"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Email</th>
<table id="myTable">
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
<th>Due</th>
<th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
<td>John</td>
<td>jsmith@example.com</td>
<td>$50.00</td>
<td>http://www.jsmith.example.com</td>
</tr>
<tr>
<td>Bach</td>
<td>Frank</td>
<td>fbach@example.com</td>
<td>$50.00</td>
<td>http://www.frank.example.com</td>
</tr>
<tr>
<td>Doe</td>
<td>Jason</td>
<td>jdoe@example.com</td>
<td>$100.00</td>
<td>http://www.jdoe.example.com</td>
</tr>
<tr>
<td>Conway</td>
<td>Tim</td>
<td>tconway@example.net</td>
<td>$50.00</td>
<td>http://www.timconway.example.com</td>
</tr>
</tbody>
</table>
这可能有点慢,我总是尽量避免嵌套循环。
是否有可能使用Dom将列视为容器
IE for (cell x in Column y)
{ doMyfunction(); }
使用jQuery
$("td", "#myTable tbody").each(function(index, elem){
// do my stuff here
});
如果你只是想设计它的样式,那么使用css会快得多
tbody tr td:nth-child(4){font-weight:bold;}
据我所知,您也可以在JQuery中使用css选择器,如果您使用JQuery,则可以使用.each()函数:
$('#myTable td').each(function () {
// action to perform. Use $(this) for changing each cell
});
如果您知道您只想更改一行中的一个特定单元格,那么一旦您知道它是哪个单元格,使用:eq()或:nth-child()选择器将允许在没有行中其他单元格的情况下操作该特定单元格
下面的代码将操作行中的第一个单元格,因为eq()的索引从0开始
$('#myTable tr td:eq(0)').each(function () {
// action to perform. Use $(this) for changing each cell
});
下面的代码仍将操作第一个子级,但n-child()的索引从1开始
$('#myTable tr td:nth-child(1)').each(function () {
// action to perform. Use $(this) for changing each cell
});
视情况而定。如果他想绑定同一个函数,那么不。如果他想基于索引做不同的事情,那么是的。非常好的函数。我甚至都不知道。
$('#myTable tr td:nth-child(1)').each(function () {
// action to perform. Use $(this) for changing each cell
});