使用 jquery 的最接近()遍历 td/tr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1565571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Traversing td/tr with jquery's closest()
提问by rashcroft3
<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;"/>
I have some jQuery code that goes like this:
我有一些像这样的 jQuery 代码:
$('.text_field').each(function(){
$(this).keyup(function(){
$(this).parent().parent().parent().find('.char_count_area').html(remainingChars);
....
As you can see, I'm trying to reach char_count_area
from text_field
in a rather inefficient manner.
It works, but it goes crazy if I alter the table design slightly.
I've tried using
正如你所看到的,我想达到char_count_area
的text_field
一个相当低效的方式。它有效,但如果我稍微改变表格设计,它会变得疯狂。我试过使用
$(this).closest('.char_count_area').html(remainingChars)
but it doesn't work (characters don't appear).
但它不起作用(字符不出现)。
How can I achieve this using closest
?
我怎样才能做到这一点closest
?
回答by Russ Cam
I've tidied your code somewhat (removed the each()
as it's not needed and better qualified your selector. Using just CSS classes is not best practice, specifying an element name too will be more performant).
我已经稍微整理了您的代码(删除了each()
因为它不是必需的并且更好地限定了您的选择器。仅使用 CSS 类不是最佳实践,指定元素名称也会提高性能)。
$('input.text_field').keyup(function(){
$(this).closest('td').next().html(remainingChars);
});
bear in mind that closest()
was added in jQuery 1.3, so if you're using an older version of jQuery then you might want to use
请记住,这closest()
是在 jQuery 1.3 中添加的,因此如果您使用的是旧版本的 jQuery,那么您可能想要使用
$('input.text_field').keyup(function(){
$(this).parent().parent().next().html(remainingChars);
});
This will be fine, so long as the <input>
remains in an element in a <td>
, and the next <td>
is the one with CSS class char_count_area
这会很好,只要<input>
a 中的元素仍然存在<td>
,而下一个<td>
是具有 CSS 类的元素char_count_area
EDIT:
编辑:
In response to your comment, here's a better solution that relies less on DOM positions
为了回应您的评论,这里有一个更好的解决方案,它更少依赖 DOM 位置
('input.text_field').keyup(function(){
$(this).parents('tr:first').find('td.char_count_area').html(remainingChars);
});