用jquery最近遍历td / tr()

时间:2009-10-14 10:53:58

标签: jquery jquery-selectors closest

<td width="162"><span class="required">*</span> Name:</td>
<td width="407">
    <label>
        <input id="store_name" class="text_field alnum" type="text" minlength="3"
        maxlength="30" size="40" name="store_name" style="color: rgb(51, 51, 51);"/>
    </label>
</td>
<td class="char_count_area" style="color: green;"/>

我有一些jQuery代码,如下所示:

$('.text_field').each(function(){
        $(this).keyup(function(){                 
            $(this).parent().parent().parent().find('.char_count_area').html(remainingChars); 
....

正如您所看到的,我正试图以相当低效的方式从char_count_area到达text_field。 它可以工作,但如果我略微改变表格设计会很疯狂。 我尝试过使用

$(this).closest('.char_count_area').html(remainingChars)

但它不起作用(不出现字符)。

如何使用closest实现此目的?

1 个答案:

答案 0 :(得分:7)

我在某种程度上整理了你的代码(删除了each()因为它不需要并且更好地限定你的选择器。仅使用CSS类不是最佳实践,指定元素名称也会更高效。)

$('input.text_field').keyup(function(){                                 
    $(this).closest('td').next().html(remainingChars);
});

请记住,jQuery 1.3中添加了closest(),所以如果你使用旧版本的jQuery,那么你可能想要使用

$('input.text_field').keyup(function(){                                 
    $(this).parent().parent().next().html(remainingChars);
});

只要<input>保留在<td>的元素中,下一个<td>是CSS类char_count_area

修改

在回应您的评论时,这是一个更好地依赖DOM位置的更好的解决方案

('input.text_field').keyup(function(){                                 
    $(this).parents('tr:first').find('td.char_count_area').html(remainingChars);
});