使用jquery在给定元素上编写的不同方法

时间:2009-09-19 11:54:22

标签: jquery

我正在尝试探索可用于简化代码的任何可能的编码选项,或者在编写代码时具有更好的灵活性。 如果我有这个元素嵌套..

<table>
   <tr><td></td><td></td></tr>
   <tr><td></td><td></td></tr>
   <tr><td></td><td></td></tr>
   <tr><td></td><td></td></tr>
</table>

如果我想在第一列上写文字,我可以

$("table tr").each(function({
  // how to write text here on all first column using $(this)?
  // other ways to write on first column?
});

//不使用“.each”

编写所有第一列的其他方法

2 个答案:

答案 0 :(得分:4)

您可以使用first选择器:

$('table tr td:first').each(function(){
    $(this).text('1st column');
});

或者不使用每个:

$('table tr td:first').text('1st column');

我希望我的评论正确。如果您出于某种原因不想先使用,可以在对每个()的调用中检查prev()是否为空。

if ($(this).prev().length == 0){
    // $(this) references the first column
}

答案 1 :(得分:1)

$("table tr").each(function({
    $(this).find('td:first').text('Some text');
});