使用jQuery的closest()遍历td/tr

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); 
....

正如您所见,我正在试图以一种相当低效的方式从text_field到达char_count_area。虽然它能工作,但是如果稍微更改表格设计,它就会变得非常混乱。我已经尝试过使用。

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

但它不起作用(字符不显示)。

我如何使用closest实现这一点?

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> 仍然在 <td> 元素中,并且下一个 <td> 是具有 CSS 类 char_count_area 的元素,那么这将是可行的。 编辑: 针对您的评论,这里有一个更好的解决方案,它更少地依赖于 DOM 位置。
('input.text_field').keyup(function(){                                 
    $(this).parents('tr:first').find('td.char_count_area').html(remainingChars);
});

好的,谢谢。有一个问题 - 有时在char_count_area之前我会有另一个<td>,所以next();永远无法到达char_count_area,我必须使用next().next().. 我希望能够普遍使用相同的javascript代码。这就是为什么我试图特别指定最接近的'.char_count_area',而不是任何'td'。有什么帮助吗? - rashcroft3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接