2011-08-01 74 views
6

嗨,我想显示数字字符与类showchars类最近的div。jQuery获得与类最接近的div

我试着这样做:

$('#maina').focus(function() { 
$(this).closest("div.showchars").find(".countchars").html("KKK"); 
    $("#error-1").html(""); 
    $(this).closest(".showchars").html("hmm"); 
}); 

有了这个网站:

<tr> 
    <td> 
    Main Alliase/Current Alliase: 
    </td> 
    <td><input type="text" id="maina" class="countchars"/><br /> 
    <div class="showchars">o</div> 
    </td> 
<td><span id="handle-1" class="selector">?</span></td> 
    <td><div id="error-1" class="errors"></div></td> 
    </tr> 

当我集中到它重置错误类的内容输入框。

但不改变文本:hmm在div。

我去哪里错了,或者有什么更好的方法来获得最接近的div,然后实现api:.html("hmm")

感谢

回答

6

.closest()着眼于元素本身及其家长进行匹配

在您的示例中,.showchars是文本框的兄弟,因此您可以使用.siblings()代替。

$(this).siblings(".showchars").html("hmm"); 

Demo here

+0

它的工作,但它会改变班级中的所有兄弟姐妹的内容或什么?谢谢 – kritya

+0

'.siblings()'可选择接受一个过滤器。你可以指定'“.showchars”'来过滤你精确需要的元素。 –

+0

是的,我知道,但我的意思是说,它会把这一切,以所有兄弟姐妹发现阶级showchars?只是问我是否可以在其他地方实施它 – kritya

1
$(this).nextAll(".showchars:first").html("hmm"); 
+0

我不认为接下来,然后选择第一个是一个很好的选择。思想感谢您的尝试:D – kritya

+0

我宁愿使用.sibling:D – kritya

+0

兄弟姐妹'也会得到所有兄弟姐妹,并用选择器过滤它们 –