选择表格第一行的输入
Posted
技术标签:
【中文标题】选择表格第一行的输入【英文标题】:Select inputs in first row of table 【发布时间】:2013-05-20 13:37:08 【问题描述】:我正在处理的页面包含一个带有标题行、几行文本输入和一个总行的表格。当用户在输入中输入数字时,将在总计行中计算每列的总和。当触发输入的change()
事件时,将运行此计算。
加载页面后,我希望能够在表格第一行的文本输入上触发change()
事件。我在确定要使用的正确选择器时遇到了一些麻烦。
表结构示例:
<table>
<tr class="tblRow headerRow">
<!-- header cells -->
</tr>
<tr class="altTblRow">
<td class="tableCell">
<input type="text" id="input1-1">
</td>
<td class="tableCell">
<input type="text" id="input1-2">
</td>
<td class="tableCell">
<input type="text" id="input1-3">
</td>
</tr>
<tr class="tblRow">
<td class="tableCell">
<input type="text" id="input2-1">
</td>
<td class="tableCell">
<input type="text" id="input2-2">
</td>
<td class="tableCell">
<input type="text" id="input2-3">
</td>
</tr>
<tr class="tblRow">
<td class="tableCell">
<input type="text" id="input3-1">
</td>
<td class="tableCell">
<input type="text" id="input3-2">
</td>
<td class="tableCell">
<input type="text" id="input3-3">
</td>
</tr>
<tr class="altTblRow totalRow">
<!-- total cells -->
</tr>
</table>
我尝试使用几个选择器,但无法获得我要查找的内容。
$('.tblRow:first input').change();
$('.tblRow input').first().change();
$('.tblRow input').parent('tr').find('input').change();
是否有一个选择器可以仅用于第一个表格行中的输入,还是我必须获取第一个 input
并使用 .parent()
获取行?
(注意:代码示例中的 ID 已更改;否则我会使用 'input[class*=input1]'
)
【问题讨论】:
【参考方案1】:我建议,虽然未经测试:
$('tr:not(".headerRow")').first().find('input').change();
JS Fiddle demo.
不过,此外,我建议您重新编写 html 以利用语义(这将简化您的 jQuery):
<table>
<thead>
<tr class="tblRow headerRow">
<!-- header cells -->
</tr>
</thead>
<tfoot>
<tr class="altTblRow totalRow">
<!-- total cells -->
</tr>
</tfoot>
<tbody>
<tr class="altTblRow">
<td class="tableCell">
<input type="text" id="input1-1">
</td>
<td class="tableCell">
<input type="text" id="input1-2">
</td>
<td class="tableCell">
<input type="text" id="input1-3">
</td>
</tr>
<!-- other rows -->
</tbody>
</table>
这将允许您简单地使用:
$('tbody tr').first().find('input').change();
JS Fiddle demo.
参考资料:
change()
。
find()
。
first()
。
:not()
selector。
【讨论】:
【参考方案2】:Insetead 使用表格行尝试 While(parameter) 并尝试它,然后看看你得到什么结果,如果你清楚,告诉我如果没有告诉我你得到的确切错误
【讨论】:
【参考方案3】:您可以选择除最后一行以外的所有行:
$('tr:not(:last-child) input')
见here
或者如果你不想要标题:
$('tr:not(:last-child):not(:first-child) input')
【讨论】:
唯一的问题是我试图只选择一行中的输入,因为表格最终会有几百个单元格(类似于 15 x 25 表格),我如果我每列只运行一个,不想让页面陷入许多计算。但是,使用$('tr:not(:last-child):not(:first-child).first().find('input)
可能会起作用。我会试一试。以上是关于选择表格第一行的输入的主要内容,如果未能解决你的问题,请参考以下文章