jQuery 使用类获取最接近的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6895056/
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
jQuery getting the closest div with a class
提问by kritya
Hii i want to show the number chars to the closest div with the class showchars
.
嗨,我想将数字字符显示到与类最近的 div 中showchars
。
I tried to do this :
我试图这样做:
$('#maina').focus(function() {
$(this).closest("div.showchars").find(".countchars").html("KKK");
$("#error-1").html("");
$(this).closest(".showchars").html("hmm");
});
With this html:
使用这个 html:
<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>
When i focus into the input boxes it does resets the content of the errors class.
当我关注输入框时,它确实会重置错误类的内容。
But doesnt changes text to : hmm
in the div.
但不会将文本更改为 :hmm
在 div 中。
Where have been i going wrong or what is the better way to get the closest div and then implement the api : .html("hmm")
?
我哪里出错了,或者获得最接近的 div 然后实现 api 的更好方法是什么:.html("hmm")
?
Thanks
谢谢
采纳答案by Salman A
.closest()
looks at the element itself and its parents for a match.
.closest()
查看元素本身和它的父元素是否匹配。
In your example, .showchars
is a sibling of the textbox so you could use .siblings()
instead.
在您的示例中,.showchars
是文本框的兄弟,因此您可以.siblings()
改用。
$(this).siblings(".showchars").html("hmm");
回答by Igor Dymov
$(this).nextAll(".showchars:first").html("hmm");