7
<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

4

1 回答 1

8

我已经对您的代码进行了一些整理(删除了它,each()因为它不需要并且更好地限定了您的选择器。仅使用 CSS 类不是最佳实践,指定元素名称也会更高效)。

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

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

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

这会很好,只要<input>保留在 a 中的一个元素中<td>,下一个<td>是带有 CSS 类的元素char_count_area

编辑:

针对您的评论,这是一个更好的解决方案,它较少依赖 DOM 位置

('input.text_field').keyup(function(){                                 
    $(this).parents('tr:first').find('td.char_count_area').html(remainingChars);
});
于 2009-10-14T11:06:28.637 回答